#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
6 min read min read

Working with JSON Data

Learn to read, write and work with JSON format

Working with JSON Data

What is JSON?

JSON stands for JavaScript Object Notation. It's a text format for storing and sharing data. Almost all web APIs use JSON.

What JSON looks like:

code.txt
{
  "name": "John",
  "age": 25,
  "city": "New York"
}

Why JSON is popular:

  • Easy for humans to read
  • Easy for computers to parse
  • Works with all programming languages
  • Standard format for web APIs
  • Lighter than XML

JSON vs Python

JSON looks very similar to Python dictionaries.

JSON types match Python:

  • JSON object → Python dictionary
  • JSON array → Python list
  • JSON string → Python string
  • JSON number → Python int or float
  • JSON true/false → Python True/False
  • JSON null → Python None

The json Module

Python has a built-in json module.

code.py
import json

What this does: Imports Python's JSON tools.

Converting Python to JSON String

This is called serialization or "dumping".

code.py
import json

person = {
    "name": "John",
    "age": 25,
    "city": "New York"
}

json_string = json.dumps(person)
print(json_string)

What dumps() does: Converts Python dictionary to JSON string.

Output:

{"name": "John", "age": 25, "city": "New York"}

Pretty Printing JSON

Make JSON easier to read.

code.py
import json

person = {
    "name": "John",
    "age": 25,
    "city": "New York",
    "hobbies": ["reading", "gaming"]
}

json_string = json.dumps(person, indent=4)
print(json_string)

What indent does: Adds spaces and line breaks for readability.

Output:

code.txt
{
    "name": "John",
    "age": 25,
    "city": "New York",
    "hobbies": [
        "reading",
        "gaming"
    ]
}

Converting JSON String to Python

This is called deserialization or "loading".

code.py
import json

json_string = '{"name": "John", "age": 25, "city": "New York"}'

person = json.loads(json_string)
print(person["name"])
print(type(person))

What loads() does: Converts JSON string to Python dictionary.

Output:

John <class 'dict'>

Writing JSON to File

Save Python data as JSON file.

code.py
import json

students = [
    {"name": "John", "grade": "A", "age": 20},
    {"name": "Sarah", "grade": "B", "age": 22},
    {"name": "Mike", "grade": "A", "age": 21}
]

with open("students.json", "w") as file:
    json.dump(students, file, indent=4)

print("Data saved to students.json")

What dump() does: Writes Python data directly to file as JSON.

Created file (students.json):

code.txt
[
    {
        "name": "John",
        "grade": "A",
        "age": 20
    },
    {
        "name": "Sarah",
        "grade": "B",
        "age": 22
    }
]

Reading JSON from File

Load JSON file into Python.

code.py
import json

with open("students.json", "r") as file:
    students = json.load(file)

print("Loaded", len(students), "students")

for student in students:
    print(student["name"], "-", student["grade"])

What load() does: Reads JSON file and converts to Python data.

Working with Nested JSON

JSON can have objects inside objects.

code.py
import json

company = {
    "name": "Tech Corp",
    "employees": [
        {
            "name": "John",
            "position": "Developer",
            "skills": ["Python", "JavaScript"]
        },
        {
            "name": "Sarah",
            "position": "Designer",
            "skills": ["Photoshop", "Figma"]
        }
    ]
}

json_string = json.dumps(company, indent=2)
print(json_string)

print("First employee:", company["employees"][0]["name"])
print("Their skills:", company["employees"][0]["skills"])

What this shows: How to access data multiple levels deep.

Handling JSON Errors

Not all strings are valid JSON.

code.py
import json

invalid_json = '{"name": "John", age: 25}'

try:
    data = json.loads(invalid_json)
except json.JSONDecodeError as e:
    print("Invalid JSON:", e)

What causes the error: Missing quotes around "age". JSON requires quotes for all keys.

Converting Lists to JSON

code.py
import json

numbers = [1, 2, 3, 4, 5]
json_string = json.dumps(numbers)
print(json_string)

back_to_list = json.loads(json_string)
print(back_to_list)

What this shows: Lists become JSON arrays and back to Python lists.

Sorting JSON Keys

code.py
import json

person = {"name": "John", "age": 25, "city": "New York"}

json_string = json.dumps(person, indent=4, sort_keys=True)
print(json_string)

What sort_keys does: Arranges keys alphabetically in output.

Output:

code.txt
{
    "age": 25,
    "city": "New York",
    "name": "John"
}

Practice Example

The scenario: Build a simple user database with JSON storage.

code.py
import json
import os

def load_users():
    if os.path.exists("users.json"):
        with open("users.json", "r") as file:
            return json.load(file)
    return []

def save_users(users):
    with open("users.json", "w") as file:
        json.dump(users, file, indent=4)

def add_user(name, email, age):
    users = load_users()

    new_user = {
        "id": len(users) + 1,
        "name": name,
        "email": email,
        "age": age
    }

    users.append(new_user)
    save_users(users)
    print("User added:", name)

def list_users():
    users = load_users()

    if not users:
        print("No users found")
        return

    print("All users:")
    for user in users:
        print("ID:", user["id"])
        print("Name:", user["name"])
        print("Email:", user["email"])
        print("Age:", user["age"])
        print()

def find_user(user_id):
    users = load_users()

    for user in users:
        if user["id"] == user_id:
            return user

    return None

add_user("John Doe", "john@example.com", 25)
add_user("Sarah Smith", "sarah@example.com", 30)

list_users()

user = find_user(1)
if user:
    print("Found user:", user["name"])

What this system does:

  1. Loads users from JSON file
  2. Adds new users with unique IDs
  3. Saves back to JSON file
  4. Lists all users
  5. Finds user by ID

Filtering JSON Data

code.py
import json

with open("students.json", "r") as file:
    students = json.load(file)

a_students = [s for s in students if s["grade"] == "A"]

print("A students:")
for student in a_students:
    print(student["name"])

What this does: Reads JSON, filters for A students, shows their names.

Updating JSON Data

code.py
import json

with open("students.json", "r") as file:
    students = json.load(file)

for student in students:
    if student["name"] == "John":
        student["grade"] = "A+"

with open("students.json", "w") as file:
    json.dump(students, file, indent=4)

print("Data updated")

What this does: Reads JSON, modifies data, writes back to file.

Key Points to Remember

JSON is a text format for data. Almost all web APIs use JSON.

json.dumps() converts Python to JSON string. json.loads() converts JSON string to Python.

json.dump() writes to file. json.load() reads from file. Remember: "s" means string, no "s" means file.

JSON requires double quotes for strings and keys. Single quotes are not valid JSON.

Use indent parameter to make JSON readable. Use try-except to handle invalid JSON.

Common Mistakes

Mistake 1: Wrong function

code.py
data = json.dumps("data.json")  # Wrong! This converts string to JSON
data = json.load(open("data.json"))  # Correct for files

Mistake 2: Single quotes in JSON

code.py
json_string = "{'name': 'John'}"  # Invalid JSON!
json_string = '{"name": "John"}'  # Correct

Mistake 3: Not handling errors

code.py
data = json.loads(user_input)  # May crash if invalid JSON!

Use try-except.

Mistake 4: Forgetting to close file

code.py
file = open("data.json", "w")
json.dump(data, file)
# Forgot file.close()

Use with statement instead.

What's Next?

You now know how to work with JSON. Next, you'll learn about XML data processing - another data format used by many systems and APIs.

SkillsetMaster - AI, Web Development & Data Analytics Courses