Sub topic 10
Nested data and JSON
This chapter assumes you can index nested lists and dictionaries with chained access, and that you know basic for loops and functions. Here you will see how Python's nested data maps to JSON, how to convert between the two, and which values do not survive the trip.
Why JSON fits nested data
JSON (JavaScript Object Notation) is a text format for structured data. Web APIs, configuration files, and many data exports use it. Its structure matches what you already build in Python.
| JSON | Python |
|---|---|
| object | dict |
| array | list |
| string | str |
| number | int or float |
| true / false | True / False |
| null | None |
Because the shapes match, a list of dictionaries or a dictionary of lists converts with no extra code.
Converting with dumps and loads
The json module is in the standard library. json.dumps() turns Python data into a JSON string. json.loads() turns a JSON string back into Python data.
import json
data = {"user": {"name": "Ana", "roles": ["admin", "dev"]}}
text = json.dumps(data, indent=2)
restored = json.loads(text)
print(restored["user"]["roles"][0]) # admin
print(restored == data) # TrueThe indent=2 argument makes the text readable by adding line breaks and spaces. Without it, the output is one compact line. Once loads() returns, you have ordinary nested Python data and can use every technique from earlier chapters: chained indexing, get(), loops, and copies.
The names are easy to mix up. The trailing s stands for "string". dumps and loads work with strings in memory. json.dump() and json.load() work with files.
import json
data = {"items": [{"id": 1}, {"id": 2}]}
with open("data.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
with open("data.json", encoding="utf-8") as f:
loaded = json.load(f)
print(loaded["items"][1]["id"]) # 2Reading API-style data safely
JSON from outside your program may lack keys you expect. Combine loads() with the safe access tools from the earlier chapter.
import json
text = '{"user": {"name": "Ben"}, "tags": ["new"]}'
payload = json.loads(text)
email = payload.get("user", {}).get("email", "unknown")
print(email) # unknownInvalid JSON raises json.JSONDecodeError, which is a subclass of ValueError. Catch it when the text comes from a user or a network.
import json
try:
json.loads("{'name': 'Ana'}")
except json.JSONDecodeError as err:
print("bad JSON:", err)This text fails because JSON requires double quotes. Single quotes are valid in Python but not in JSON.
What does not round-trip
Round-tripping means converting to JSON and back and expecting the same data. Some Python values change or fail.
import json
data = {1: "one", "pair": (1, 2)}
restored = json.loads(json.dumps(data))
print(restored) # {'1': 'one', 'pair': [1, 2]}
print(restored == data) # FalseTwo changes happened here. JSON object keys must be strings, so the integer key 1 became "1". JSON has no tuple, so the tuple became a list.
Other types are not supported at all. A set, a datetime, or a custom object makes dumps() raise TypeError.
import json
try:
json.dumps({"ids": {1, 2, 3}})
except TypeError as err:
print(err) # Object of type set is not JSON serializableThe usual fix is to convert before dumping, for example sorted(ids) for a set or when.isoformat() for a date.
The flow of a round trip
Common errors
- Passing a file object to
loads(), or a string toload(). Match the function to the source. - Writing JSON by hand with single quotes or trailing commas. Both are invalid.
- Expecting
Truein the text. JSON uses lowercasetrue, anddumps()writes it that way. - Assuming the loaded data has the shape you expect. Check keys with
get()orin.
Exercise
You run json.loads(json.dumps({"point": (3, 4), 7: "seven"})). What does the result look like, and why is it not equal to the original?
Show answer
The result is {'point': [3, 4], '7': 'seven'}. JSON has no tuple, so (3, 4) becomes the list [3, 4]. JSON object keys must be strings, so the integer key 7 becomes '7'. The dictionaries differ in both a value and a key, so == returns False.
Exercise
Write code that loads the string '{"orders": [{"id": 1, "total": 20}, {"id": 2}]}' and prints the sum of all order totals, treating a missing total as 0.
Show answer
import json text = '{"orders": [{"id": 1, "total": 20}, {"id": 2}]}' data = json.loads(text) print(sum(order.get("total", 0) for order in data["orders"])) # 20