Sub topic 2
What JSON is and how it maps to Python types
This chapter assumes you know basic Python syntax, dicts, lists, and strings. It covers what JSON is and how its values become Python objects and back. The next chapter uses the json functions that do the conversion.
What JSON is
JSON (JavaScript Object Notation) is a text format for structured data. It is language independent, so a Python program, a browser, and a web API can all exchange it. A JSON document is plain text built from six kinds of value:
- Objects:
{"name": "Ada"}, a set of key-value pairs. - Arrays:
[1, 2, 3], an ordered list of values. - Strings:
"hello", always in double quotes. - Numbers:
42,-3.5,1e6. - Booleans:
trueandfalse, in lowercase. - Null:
null, meaning "no value".
Values nest freely. An object can hold arrays, and an array can hold objects.
The type mapping
The json module converts between JSON text and Python objects using this table.
| JSON | Python (after loading) |
|---|---|
| object | `dict` |
| array | `list` |
| string | `str` |
| number without a fraction or exponent | `int` |
| number with a fraction or exponent | `float` |
| `true` / `false` | `True` / `False` |
| `null` | `None` |
You can check the mapping by loading a document and printing the type of each value:
import json
text = '{"name": "Ada", "langs": ["Python", "C"], "active": true, "score": null, "ratio": 1.5, "count": 3}'
data = json.loads(text)
for key, value in data.items():
print(key, type(value).__name__)This prints str, list, bool, NoneType, float, and int for the six keys, in order. The result is ordinary Python data, so you work with it using normal dict and list operations.
The mapping is not symmetric
Going from Python to JSON is not the exact reverse of going from JSON to Python. Several Python values change on the way, and a few cannot be converted at all.
| Python value | JSON result | Loads back as |
|---|---|---|
| `tuple` | array | `list` |
| `dict` with `int` keys | object with string keys | `dict` with `str` keys |
| `True` / `None` | `true` / `null` | `True` / `None` |
| `set`, `datetime`, custom class | `TypeError` | not applicable |
A round trip shows the loss:
import json
original = {1: "one", "pair": (1, 2)}
restored = json.loads(json.dumps(original))
print(restored) # {'1': 'one', 'pair': [1, 2]}
print(restored == original) # FalseThe integer key 1 became the string "1", and the tuple became a list. JSON has no tuple type, and its object keys must be strings. Code that reads such data back has to expect these changes.
Types that JSON has no equivalent for, such as sets and dates, raise TypeError when you try to serialize them. A later chapter shows how to handle them with the default parameter.
Common errors
Most JSON errors at this level come from writing JSON as if it were Python. The rules below are strict.
- Strings and keys need double quotes.
{'a': 1}is valid Python but invalid JSON. - Booleans and null are lowercase.
TrueandNoneare not valid JSON. - Trailing commas are not allowed.
[1, 2,]is invalid. - Comments are not allowed.
- Keys must be strings. Python's
dumpsconverts simple keys such as1for you, but this is why they come back as strings.
Numbers and precision
JSON itself does not distinguish integers from floats. Python decides from the text. 3 loads as int, while 3.0 and 3e0 load as float. Python integers have no size limit, so 12345678901234567890 loads exactly. Other languages, such as JavaScript, store every number as a 64-bit float and may round it. If you exchange large IDs with such systems, send them as strings.
Summary
JSON has six value types, and each has a direct Python counterpart. Loading gives you dict, list, str, int, float, bool, and None. Dumping is lossy for tuples and non-string keys, and it fails for types JSON lacks. Keep the strict syntax rules in mind when you write JSON by hand.
Exercise
What does json.loads(json.dumps({"ok": True, "tags": ("a", "b"), 2: None})) return, and why does it differ from the input?
Show answer
It returns {'ok': True, 'tags': ['a', 'b'], '2': None}. The tuple becomes a list because JSON only has arrays, and the integer key 2 becomes the string "2" because JSON object keys must be strings. True and None survive because they map to true and null.
Exercise
A colleague sends the text {'active': True,} and says it is JSON. List the three problems that make it invalid.
Show answer
The key and string use single quotes instead of double quotes, True must be lowercase true, and the trailing comma before the closing brace is not allowed.