Python JSON — Serialization & Data Exchange
JSON (JavaScript Object Notation) is the standard data interchange format. Python's json module handles encoding and decoding.
Learning Objectives
- Serialize Python objects to JSON strings
- Deserialize JSON to Python objects
- Customize JSON serialization for complex types
- Handle large JSON files with streaming
Basic Encoding and Decoding
import json
# Python dict to JSON string
data = {
"name": "Alice",
"age": 30,
"scores": [95, 87, 91],
"active": True
}
json_string = json.dumps(data, indent=2)
print(json_string)
# JSON string to Python dict
parsed = json.loads(json_string)
print(parsed["name"]) # "Alice"
File Operations
import json
# Write JSON to file
data = {"users": [{"name": "Alice"}, {"name": "Bob"}]}
with open('data.json', 'w') as f:
json.dump(data, f, indent=2)
# Read JSON from file
with open('data.json', 'r') as f:
loaded = json.load(f)
Custom Serialization
import json
from datetime import datetime, date
class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, (datetime, date)):
return obj.isoformat()
if isinstance(obj, set):
return list(obj)
if hasattr(obj, '__dict__'):
return obj.__dict__
return super().default(obj)
data = {
"event": "Conference",
"date": datetime.now(),
"tags": {"python", "tech"},
"attendees": 500
}
json_str = json.dumps(data, cls=CustomEncoder, indent=2)
Advanced Options
import json
data = {"name": "Alice", "age": 30, "city": "NYC"}
# Compact output
compact = json.dumps(data, separators=(',', ':'))
# '{"name":"Alice","age":30,"city":"NYC"}'
# Sort keys
sorted_json = json.dumps(data, sort_keys=True)
# Handle non-serializable objects
def handle_non_serializable(obj):
return str(obj)
json.dumps({"date": datetime.now()}, default=handle_non_serializable)
# Parse with object_hook for custom decoding
def as_complex(dct):
if '__complex__' in dct:
return complex(dct['real'], dct['imag'])
return dct
JSON Streaming
import json
# Write large JSON arrays incrementally
def write_large_json(filename, items):
with open(filename, 'w') as f:
f.write('[\n')
for i, item in enumerate(items):
json.dump(item, f)
if i < len(items) - 1:
f.write(',\n')
f.write('\n]')
# Read large JSON files
def read_large_json(filename):
with open(filename, 'r') as f:
for line in f:
yield json.loads(line)
Key Takeaways
json.dumps()encodes Python objects to JSON stringsjson.loads()decodes JSON strings to Python objects- Use
indentfor pretty-printing - Custom encoder for non-standard types
- JSON is text — use streaming for large data