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
- Load and parse complex nested JSON
- Convert list of dictionaries to JSON
- Handle JSON with missing fields
- Merge multiple JSON files
- Validate JSON schema