Python Lesson 23: Working with JSON

🐍 Python CourseLesson 23 of 26 · 88% complete

JSON (JavaScript Object Notation) is the universal language for data on the internet. Almost every API returns JSON. Understanding JSON is essential for modern Python programming.

What JSON Looks Like

# JSON is text that looks like Python dicts/lists:
{
  "name": "Alice",
  "age": 30,
  "is_student": false,
  "scores": [95, 87, 92],
  "address": {
    "city": "London",
    "country": "UK"
  }
}

# Rules:
# - Keys are always in double quotes
# - true/false (lowercase, not Python True/False)
# - null instead of None
# - No trailing commas

Parsing JSON in Python

import json

# JSON string (what you receive from an API)
json_string = '{"name": "Alice", "age": 30, "city": "London"}'

# Parse: JSON string -> Python dict
person = json.loads(json_string)

print(person["name"])   # Alice
print(person["age"])    # 30
print(type(person))     # dict

Converting Python to JSON

import json

user = {
    "name": "Bob",
    "age": 25,
    "languages": ["Python", "JavaScript"],
    "active": True
}

# Convert: Python dict -> JSON string
json_str = json.dumps(user)
print(json_str)
# {"name": "Bob", "age": 25, "languages": ["Python", "JavaScript"], "active": true}

# Pretty print with indentation
pretty = json.dumps(user, indent=2)
print(pretty)

Reading/Writing JSON Files

import json

# Save dict to JSON file
data = {"users": [{"name":"Alice","score":95}, {"name":"Bob","score":87}]}

with open("data.json", "w") as f:
    json.dump(data, f, indent=2)

# Read JSON file back into Python
with open("data.json", "r") as f:
    loaded = json.load(f)

print(loaded["users"][0]["name"])  # Alice
print(loaded["users"][1]["score"]) # 87

Nested JSON Navigation

api_response = {
    "status": "success",
    "data": {
        "user": {
            "id": 42,
            "name": "Alice",
            "skills": ["Python", "Django", "SQL"]
        }
    }
}

# Navigate nested structure
name = api_response["data"]["user"]["name"]
skill = api_response["data"]["user"]["skills"][0]
print(name, skill)  # Alice Python

🏋️ Practice Task

Create a contacts.json file that stores 3 contacts (name, email, phone). Write Python code to: (1) load the JSON file, (2) print all contacts, (3) add a new contact, (4) save back to the file.

💡 Hint: Use json.load() to read, json.dump() to write. Use list.append() to add a new contact dict.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *