w3resource

Mastering JSON Files: A Beginner’s Guide with Python Examples


Understanding JSON File: Storing and Accessing Data

A JSON (JavaScript Object Notation) file is a lightweight data-interchange format used to store and transmit data. It is human-readable and structured as key-value pairs, making it widely used in APIs, configuration files, and data storage.

JSON is language-independent and easily parsed by various programming languages.


Structure of a JSON File:

A JSON file typically consists of one of the following:

    1. Object: A collection of key-value pairs enclosed in curly braces {}.

    2. Array: An ordered list of values enclosed in square brackets [].


Syntax:

Key Characteristics:

    1. Key-value pairs are separated by colons :.

    2. Keys are strings enclosed in double quotes ".

    3. Values can be:

    • Strings (enclosed in double quotes)
    • Numbers (integers or floating-point)
    • Booleans (true or false)
    • Null
    • Arrays
    • Objects

Example JSON file:

example.json:

Code:

{
  "name": "Lupus Sundri",
  "age": 30,
  "isEmployed": true,
  "skills": ["Python", "JavaScript", "SQL"],
  "address": {
    "city": "New York",
    "zip": "10001"
  }
}

Examples and Code:

Example 1: Reading a JSON File in Python

Code:

import json  # Import the JSON module

# Open the JSON file in read mode
with open('example.json', 'r') as file:
    # Load the contents of the file into a Python dictionary
    data = json.load(file)

# Access data from the dictionary
print("Name:", data["name"])  # Print the name key
print("City:", data["address"]["city"])  # Print the city from the address

Output:

Name: Lupus Sundri
City: New York

Explanation:

  • json.load(file): Converts the JSON content into a Python dictionary.
  • Nested keys can be accessed using the dictionary syntax.

Example 2: Writing to a JSON File

Code:

import json  # Import the JSON module

# Create a Python dictionary
person = {
    "name": "Svatoslav Ismini",
    "age": 25,
    "isEmployed": False,
    "skills": ["HTML", "CSS"],
    "address": {"city": "San Francisco", "zip": "94103"}
}

# Write the dictionary to a JSON file
with open('output.json', 'w') as file:
    json.dump(person, file, indent=4)  # Save with indentation for readability

# Confirm the file is saved
print("JSON file has been created as 'output.json'")

Output:

JSON file has been created as 'output.json'

Explanation:

  • json.dump(obj, file, indent=4): Writes the Python dictionary obj into the file with readable indentation.

Content of output.json:

{
    "name": "Svatoslav Ismini",
    "age": 25,
    "isEmployed": false,
    "skills": [
        "HTML",
        "CSS"
    ],
    "address": {
        "city": "San Francisco",
        "zip": "94103"
    }
}

Example 3: Modifying a JSON File

Code:

import json  # Import the JSON module

# Open and load the JSON file
with open('example.json', 'r') as file:
    data = json.load(file)

# Modify the data
data["age"] = 35  # Update the age
data["skills"].append("Django")  # Add a new skill

# Save the updated data back to the file
with open('example.json', 'w') as file:
    json.dump(data, file, indent=4)  # Save with indentation

print("JSON file updated successfully.")

Output:

JSON file updated successfully.

Explanation:

  • JSON files can be edited by loading them as dictionaries, modifying their content, and saving them back.

Content of modified example.json file:

Code:

{
    "name": "Lupus Sundri",
    "age": 35,
    "isEmployed": true,
    "skills": [
        "Python",
        "JavaScript",
        "SQL",
        "Django"
    ],
    "address": {
        "city": "New York",
        "zip": "10001"
    }
}

Example 4: JSON File Validation

Code:

import json

# Define a string with JSON content
json_content = '{"name": "Rabi Ivo", "age": 28, "isEmployed": true}'

try:
    # Validate if the string is valid JSON
    data = json.loads(json_content)
    print("Valid JSON:", data)
except json.JSONDecodeError as e:
    print("Invalid JSON:", e)

Output:

Valid JSON: {'name': 'Rabi Ivo', 'age': 28, 'isEmployed': True} 

Explanation:

  • Use json.loads to validate and parse JSON strings in Python.

Key Notes:

    1. Human Readable: JSON is easy for humans to read and write.

    2. Cross-Platform: JSON is supported by many programming languages.

    3. Flexibility: It can handle complex data structures like nested objects and arrays.

    4. Validation: Always validate JSON content to ensure it is properly formatted.


Additional Information:

  • JSON is case-sensitive.
  • It is commonly used for data exchange between servers and clients in web applications.
  • Tools like JSONLint help validate and format JSON files.

Practical Guides to JSON Snippets and Examples.



Follow us on Facebook and Twitter for latest update.