JSON
- Parse JSON strings into Python objects with
json.loads - Serialize Python objects to JSON with
json.dumps - Handle nested JSON data returned from APIs
- Deal with dates, sets, and other non-JSON-native types
Every REST API, config file, and log aggregator (Datadog, ELK) speaks JSON. Python's json module can't serialize datetime, Decimal, or set out of the box — a TypeError that hits every new backend engineer. orjson is 5-10x faster for hot paths.
- Serializing
datetimeorDecimaldirectly — pass a customdefault=handler or usepydantic/orjson. - Using
json.loadson untrusted large payloads without a size cap — memory-exhaustion DoS vector. - Round-tripping floats and expecting exact equality — JSON has no
Decimal; keep money as strings.
JSON is how systems exchange data. Python's json module converts both ways.
The two calls
json.dumps(obj, indent=2)— Python → JSON stringjson.loads(text)— JSON string → Python
Type mapping
| Python | JSON |
|---|---|
| dict | object |
| list, tuple | array |
| str | string |
| int, float | number |
| True, False | true, false |
| None | null |
Try it
- Parse
'{"a": 1, "b": [2, 3]}'and printb's sum. - Serialize
{"date": datetime.date.today()}— what error do you get? Why?
3 graded exercises
Write the code, click Check. We’ll tell you exactly what to fix.
- Exercise 1
Parse the JSON string
'{"a": 1, "b": [2, 3, 4]}'and print the sum of the values inb. Expected:9. - Exercise 2
Given
data = {"name": "Ada", "skills": ["math", "engineering"]}, convert to a JSON string with 2-space indentation and print it. Expected includes"name": "Ada"on its own line. - Exercise 3
Given a JSON string of an array of user objects, parse it and print just the name of the oldest user. Expected:
Linus.