Working with JSON

Intermediate PythonData SerializationFree Lesson

Advertisement

Introduction

JSON (JavaScript Object Notation) is a lightweight data interchange format.

Parsing JSON

import json

# JSON string to Python object
json_string = '{"name": "John", "age": 30, "city": "NYC"}'
data = json.loads(json_string)
print(data["name"])  # John

# From file
with open("data.json", "r") as f:
    data = json.load(f)

Creating JSON

# Python object to JSON string
data = {"name": "John", "age": 30, "scores": [95, 88, 92]}
json_string = json.dumps(data)

# Pretty print
json_string = json.dumps(data, indent=2)

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

Custom Serialization

from datetime import datetime

# Custom encoder
class CustomEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.isoformat()
        return super().default(obj)

data = {"timestamp": datetime.now()}
json.dumps(data, cls=CustomEncoder)

Practice Problems

  1. Load and parse complex nested JSON
  2. Convert list of dictionaries to JSON
  3. Handle JSON with missing fields
  4. Merge multiple JSON files
  5. Validate JSON schema

Advertisement

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement