Sub topic 10
Nested data and JSON
JSON is the text format most programs use to store and exchange nested data. Python's dictionaries and lists map onto it almost one to one. This chapter covers how the json module converts between the two, which values change or fail in the conversion, and how to read JSON you don't control.
This chapter assumes you can index nested lists and dictionaries, loop over them, and use get(). It also assumes you know what a shared reference is, from the chapters on aliasing and copying.
How JSON maps to Python
JSON has two container types. An object is a set of "key": value pairs, and an array is an ordered list of values. Python's dict and list fill those roles, so nesting carries over without changes.
| JSON | Python (after `loads`) | Python (accepted by `dumps`) |
|---|---|---|
| object | `dict` | `dict` |
| array | `list` | `list`, `tuple` |
| string | `str` | `str` |
| number (integer) | `int` | `int` |
| number (fraction or exponent) | `float` | `float` |
| `true` / `false` | `True` / `False` | `True` / `False` |
| `null` | `None` | `None` |
The right-hand column is narrower than Python's own data model. Sets, dates, custom objects and bytes have no JSON form, and the sections below show what happens to them.
Converting with dumps and loads
json.dumps() turns a Python structure into a string. json.loads() turns a string back into a structure. The "s" stands for "string".
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) # TrueEquality holds here because every value in data survives the trip unchanged. restored is a new structure with the same contents, not the same objects. That difference matters later.
Three dumps options come up often:
indent=2produces readable, multi-line output. Without it, the output is a single line.sort_keys=Truewrites keys in alphabetical order, which makes the output stable for diffs and tests.separators=(",", ":")removes the spaces after commas and colons, for compact output.
By default, ensure_ascii=True escapes non-ASCII characters as \uXXXX. Pass ensure_ascii=False if you want readable text such as "é" in the output, and write files with encoding="utf-8".
What changes in the round trip
A round trip does not always return what you started with. Three changes are common.
- Keys become strings. JSON object keys must be strings. Python converts
int,float,boolandNonekeys to strings when dumping. - Tuples become lists. JSON has only arrays, so the tuple/list distinction is lost.
- Types are not restored.
loadsnever recreates sets, tuples, dates, or integer keys.
import json
data = {1: "one", "pair": (1, 2), "ok": True, "none": None}
text = json.dumps(data)
print(text) # {"1": "one", "pair": [1, 2], "ok": true, "none": null}
back = json.loads(text)
print(back) # {'1': 'one', 'pair': [1, 2], 'ok': True, 'none': None}
print(back == data) # False
print(back["1"]) # oneThe lookup back[1] would now raise KeyError, because the key is the string "1". This is the most common bug in code that reads JSON back in. Convert keys explicitly after loading if you need integers, for example with {int(k): v for k, v in back.items()}.
A second key problem is collisions. json.dumps({1: "a", "1": "b"}) writes two entries with the same key "1". On loading, the later one wins and the earlier one is lost without any error.
Values that cannot be serialized
When dumps meets a type it does not know, it raises TypeError. You can fix this by passing a default function. json calls it only for objects it cannot handle, and it must return something serializable or raise TypeError.
import json
from datetime import date
record = {"title": "Report", "tags": {"a", "b"}, "due": date(2026, 12, 1)}
try:
json.dumps(record)
except TypeError as err:
print(err) # Object of type set is not JSON serializable
def encode(obj):
if isinstance(obj, set):
return sorted(obj)
if isinstance(obj, date):
return obj.isoformat()
raise TypeError(f"Cannot serialize {type(obj).__name__}")
print(json.dumps(record, default=encode))
# {"title": "Report", "tags": ["a", "b"], "due": "2026-12-01"}The encoder is applied at any depth, including inside nested lists and dictionaries. It is lossy, though. When you load this text again, tags is a list and due is a string. The code that loads the data has to convert them back. Sorting the set also gives a stable order, since sets have none.
Two more values cause trouble:
float("nan")and infinity are written asNaNandInfinity. Those are not valid JSON, and many parsers outside Python reject them. Passallow_nan=Falseto makedumpsraiseValueErrorinstead.- A structure that contains itself (a circular reference) raises
ValueError: Circular reference detected.
Files: dump and load
json.dump() and json.load() (no "s") work with open file objects instead of strings.
import json
from pathlib import Path
path = Path("settings.json")
settings = {"theme": "dark", "recent": ["a.txt", "b.txt"]}
with path.open("w", encoding="utf-8") as f:
json.dump(settings, f, indent=2)
with path.open(encoding="utf-8") as f:
loaded = json.load(f)
print(loaded["recent"][1]) # b.txt
try:
json.loads("{'theme': 'dark'}")
except json.JSONDecodeError as err:
print(err.msg, err.lineno, err.colno)
# Expecting property name enclosed in double quotes 1 2Note the failed parse at the end. JSON requires double quotes, so a Python-style dictionary literal is not valid JSON. Other common causes of JSONDecodeError are trailing commas, comments, and unquoted keys. The exception has msg, lineno, colno and pos attributes, which make useful error messages for users.
If a file might be half-written or hand-edited, catch json.JSONDecodeError. It is a subclass of ValueError, so except ValueError also catches it.
Reading JSON you did not write
Parsed JSON is just nested dictionaries and lists, so everything from the earlier chapters applies. The difference is trust. Data from an API or a user file can be missing keys, have the wrong types, or be nested differently than you expected. loads checks syntax only, not structure.
A few habits keep you safe:
- Use
.get()with defaults for optional keys, and chain it with{}defaults for optional objects. - Check types with
isinstance()before indexing. A field you expect to be a list may benull(which loads asNone) or a single object. - Treat a missing required key as an error, with a clear message, rather than letting a bare
KeyErrorescape from deep inside your code.
import json
raw = '{"user": {"name": "Ana", "roles": null}}'
data = json.loads(raw)
user = data.get("user") or {}
roles = user.get("roles") or [] # null becomes None, so use "or"
if not isinstance(roles, list):
raise ValueError("roles must be a list")
print(user.get("name", "unknown"), roles) # Ana []Here user.get("roles", []) would not be enough. The key exists, so the default is ignored and you get None. Using or [] handles both a missing key and an explicit null. The trade-off is that or also replaces other falsy values such as 0 or "", so use it only where those are not meaningful.
For large or critical inputs, a validation library or a schema is better than hand-written checks. For small scripts, the checks above are enough.
Aliasing disappears in a round trip
Inside Python, two keys can point to the same list. JSON text has no way to express that. Each occurrence is written out in full, and each load builds a separate object.
import json
shared = [1, 2]
data = {"a": shared, "b": shared}
print(data["a"] is data["b"]) # True
copy = json.loads(json.dumps(data))
print(copy["a"] is copy["b"]) # False
copy["a"].append(3)
print(copy["b"]) # [1, 2]This has two consequences. First, a dump-and-load cycle breaks any sharing your program relied on. Second, it can be used as a quick way to deep copy data made only of JSON types: json.loads(json.dumps(x)). It works, but it converts tuples to lists, turns integer keys into strings, and fails on sets and dates. For general copying, copy.deepcopy() is the better tool, because it keeps types and preserves shared references. The JSON round trip is acceptable only when you want JSON-normalized data anyway.
Transforming nested JSON
After loading, you often reshape the data. The traversal patterns from earlier chapters apply directly. For example, to normalize every key in arbitrarily nested JSON, use recursion:
def lower_keys(value):
if isinstance(value, dict):
return {k.lower(): lower_keys(v) for k, v in value.items()}
if isinstance(value, list):
return [lower_keys(item) for item in value]
return value
print(lower_keys({"Name": "Ana", "Tags": [{"ID": 1}]}))
# {'name': 'Ana', 'tags': [{'id': 1}]}This function returns new containers instead of modifying the input, which avoids surprises when the original data is still in use elsewhere. It assumes keys are strings, which is always true for data that came from loads.
Summary of decisions
| Situation | Use |
|---|---|
| Need a string (network, logging) | `dumps` / `loads` |
| Need a file | `dump` / `load` with `encoding="utf-8"` |
| Readable diffs and tests | `indent=2`, `sort_keys=True` |
| Sets, dates, custom types | `default=` function, plus conversion code on load |
| Untrusted or optional fields | `.get()`, `isinstance()`, catch `JSONDecodeError` |
| Need an exact copy with types | `copy.deepcopy()`, not a JSON round trip |
Exercise
You run json.loads(json.dumps({2: ["x"], "k": (1, 2)})). What does the result look like, and why does result[2] fail?
Show answer
The result is {'2': ['x'], 'k': [1, 2]}. JSON object keys must be strings, so the integer key 2 is written as "2", and result[2] raises KeyError because the key is now the string '2'. The tuple also becomes a list, because JSON has only arrays.
Exercise
A config file contains {"servers": null}. Why does config.get("servers", []) return None instead of [], and what expression gives an empty list in both the missing-key and null cases?
Show answer
get() returns its default only when the key is absent. Here the key exists with the value None (JSON null), so None is returned. Use config.get("servers") or [], which gives [] for a missing key and for null. It also replaces other falsy values such as an empty list, which is harmless here.
Exercise
Write a default function that lets json.dumps handle a set of numbers and a bytes value (encode bytes as a hex string). What should the function do for any other type?
Show answer
def encode(obj):
if isinstance(obj, set):
return sorted(obj)
if isinstance(obj, bytes):
return obj.hex()
raise TypeError(f"Cannot serialize {type(obj)._name_}")
Raising TypeError for unknown types keeps the normal error behavior, so unsupported values are reported instead of being silently dropped. Use it as json.dumps(data, default=encode).