JSON and Python Type Mapping
JSON has fewer types than Python. When converting, Python types map to their JSON equivalents:
| Python | JSON |
|---|---|
| dict | object |
| list, tuple | array |
| str | string |
| int, float | number |
| True/False | true/false |
| None | null |
This works both ways when parsing.
Some Python types don't have JSON equivalents:
import json
from datetime import datetime
data = {"timestamp": datetime.now()}
json.dumps(data) # TypeError!
Dates, sets, and custom objects need special handling. You'll need to convert them to strings or basic types first.
data = {"timestamp": datetime.now().isoformat()}
json.dumps(data) # Works - it's a string now
I explain type conversion in my JSON with Python course.