Sub topic 2
What JSON is and how it maps to Python types
This chapter assumes you know basic Python syntax, how dicts, lists, and strings work, how to open files with with, and how to catch exceptions. You do not need any earlier JSON experience. The chapter covers the JSON data model and how the json module converts between JSON values and Python objects. Reading and writing files comes in the next chapter.
What JSON is
JSON (JavaScript Object Notation) is a text format for structured data. It is defined by RFC 8259 and ECMA-404. Despite the name, it is language-independent. Nearly every language and web API can read and write it.
A JSON document is a string of Unicode text. It contains exactly one value, and that value is built from six kinds of building block:
- Object: an unordered collection of
"key": valuepairs inside{}. Keys must be strings in double quotes. - Array: an ordered list of values inside
[]. - String: text in double quotes. Single quotes are not allowed.
- Number: decimal digits with an optional minus sign, fraction, and exponent. There is no separate integer type.
- Boolean: the lowercase literals
trueandfalse. - Null: the lowercase literal
null.
JSON has no comments, no trailing commas, no date type, no binary type, and no way to say "this number is an integer". Everything else you want to store has to be encoded using these six kinds, and the later chapters on custom types and CSV conversion build on that fact.
The json module in the standard library does the conversion in both directions. Turning Python objects into JSON text is called serializing or encoding. Turning JSON text into Python objects is called deserializing or decoding.
The type mapping
Decoding follows this table.
| JSON | Python |
|---|---|
| object | `dict` |
| array | `list` |
| string | `str` |
| number with no fraction or exponent | `int` |
| number with a fraction or exponent | `float` |
| `true` | `True` |
| `false` | `False` |
| `null` | `None` |
Encoding goes the other way, with two additions.
| Python | JSON |
|---|---|
| `dict` | object |
| `list`, `tuple` | array |
| `str` | string |
| `int`, `float` | number |
| `True` | `true` |
| `False` | `false` |
| `None` | `null` |
The tuple row is the first asymmetry. A tuple is encoded as an array, but an array is always decoded as a list. A round trip therefore changes the type.
Decoding in practice
The following example parses one document that contains every kind of value and prints the Python type of each top-level entry.
import json
text = '{"id": 7, "price": 19.5, "tags": ["a", "b"], "active": true, "note": null, "dims": {"w": 2, "h": 3}}'
data = json.loads(text)
for key, value in data.items():
print(key, type(value).__name__, value)The output is:
id int 7
price float 19.5
tags list ['a', 'b']
active bool True
note NoneType None
dims dict {'w': 2, 'h': 3}Two details are worth noting. The result is an ordinary dict, and it keeps the order in which keys appeared in the text, because Python dicts preserve insertion order. JSON itself does not promise any order, so do not build a protocol that depends on key order. Also, null becomes None, so use is None to test for it.
Numbers: int, float, and precision
The decoder decides between int and float by looking at the text of the number.
import json
print(json.loads("1"), json.loads("1.0"), json.loads("1e2"))
print(type(json.loads("12345678901234567890123")))This prints 1 1.0 100.0 and then <class 'int'>. Note that 1e2 becomes the float 100.0, even though it is mathematically a whole number. Python integers have unlimited size, so very large integers decode exactly.
That exactness can cause trouble elsewhere. JavaScript, and many other JSON consumers, store every number as a 64-bit float. Integers above 2**53 (9,007,199,254,740,992) lose precision there. If you exchange large identifiers with such systems, send them as strings.
Floats have a different problem: binary floating point cannot represent values like 19.99 exactly. When you need exact decimal arithmetic, for example with money, pass parse_float to loads so that every fractional number is created by a function you choose.
import json
from decimal import Decimal
data = json.loads('{"price": 19.99}', parse_float=Decimal)
print(data) # {'price': Decimal('19.99')}Decimal is built from the original text of the number, so no precision is lost. The matching parse_int parameter exists but is rarely needed.
NaN and Infinity: Python accepts more than JSON allows
The JSON standard has no way to write "not a number" or infinity. Python's json module accepts and emits them anyway by default, using the JavaScript-style names NaN, Infinity, and -Infinity.
import json
print(json.loads("[NaN, Infinity, -Infinity]"))
print(json.dumps([float("nan")]))
try:
json.dumps([float("nan")], allow_nan=False)
except ValueError as e:
print("rejected:", type(e).__name__)The output is:
[nan, inf, -inf]
[NaN]
rejected: ValueErrorThe text [NaN] is not valid JSON, and strict parsers in other languages will refuse it. If your output goes to another system, pass allow_nan=False so that the problem surfaces as an exception in your code instead of as a failure in someone else's.
Keys are always strings
A JSON object key must be a string, but a Python dict key can be many things. When encoding, json converts some non-string keys to strings and rejects the rest.
intandfloatkeys become their decimal text, so2becomes"2".True,False, andNonebecome"true","false", and"null".- Any other key type, such as a tuple, raises
TypeError. You can passskipkeys=Trueto silently drop such entries, but this hides data loss.
The conversion is one-way. Decoding always gives back string keys.
import json
original = {"point": (1, 2), 2: "two", None: "nothing", 1.5: "float"}
text = json.dumps(original)
restored = json.loads(text)
print(text)
print(restored)
print(original == restored)The output is:
{"point": [1, 2], "2": "two", "null": "nothing", "1.5": "float"}
{'point': [1, 2], '2': 'two', 'null': 'nothing', '1.5': 'float'}
FalseThis round trip lost information in two ways. The tuple became a list, and the non-string keys became strings. The two dicts are not equal. The conversion can also create duplicate keys. The dict {1: "a", "1": "b"} has two distinct keys in Python, but both become "1" in JSON, and the resulting text contains the same key twice.
Duplicate keys in input
The standard says object keys "SHOULD be unique" but does not forbid duplicates, and parsers disagree about what to do. Python keeps the last value.
import json
print(json.loads('{"a": 1, "a": 2}')) # {'a': 2}No error is raised, so a malformed or malicious document can silently override an earlier value. If duplicates matter to you, pass an object_pairs_hook that receives the list of (key, value) pairs and can check them before building the dict.
What a round trip preserves
You can use this table to judge whether json.loads(json.dumps(x)) == x holds for your data.
| Python value | After a round trip | Preserved? |
|---|---|---|
| `str`, `int`, `bool`, `None` | same | yes |
| `float` (finite) | same value | yes |
| `float('nan')` | `nan`, which never equals itself | no |
| `list` | `list` | yes |
| `tuple` | `list` | no |
| `dict` with `str` keys | `dict` | yes |
| `dict` with `int` keys | `dict` with `str` keys | no |
| `set`, `bytes`, `datetime`, `Decimal` | `TypeError` on encoding | no |
For the last row, the encoder does not guess. It raises an error such as TypeError: Object of type set is not JSON serializable. A later chapter in this tutorial shows how to teach json.dumps about those types with the default parameter.
Top-level values and `loads` input
A JSON document does not have to be an object or an array. Since RFC 7159, any value may stand alone, and Python follows that.
import json
print(json.loads("42")) # 42
print(json.loads('"hello"')) # hello
print(json.loads("null")) # None
print(json.dumps(None)) # nullTwo points about the input to loads are easy to miss:
- Python's
json.loadsacceptsstr,bytes, andbytearray. For bytes, it detects UTF-8, UTF-16, or UTF-32 automatically. - The result of
loadsdepends on the text, so the type is not known in advance. Code that handles external data should check it withisinstancebefore relying on it, for example confirming that a document is adictbefore calling.get().
Common mistakes
- Treating JSON as Python syntax. Python literals
True,False, andNoneare not valid JSON. The JSON versions aretrue,false, andnull. Likewise, JSON requires double quotes. Callingstr(some_dict)does not produce JSON, andjson.loads(str(some_dict))will fail for that reason. - Expecting types to survive. Tuples, sets, and non-string keys change or fail. Design the structure you store with only the six JSON kinds in mind.
- Forgetting the string/number difference. The JSON text
"5"decodes to thestr'5', not the int5. Mixing them up leads to comparisons that are silently false. - Assuming integers are safe everywhere. Python decodes large integers exactly, but other consumers might not.
Exercise
Predict the value of restored and whether restored == original is true, without running the code.
original = {"a": (1, 2), "b": None, 3: True}
restored = json.loads(json.dumps(original))
Show answer
restored is {'a': [1, 2], 'b': None, '3': True}. The comparison is False. The tuple (1, 2) became the list [1, 2], and the int key 3 became the string key '3'. None and True survive, because they map to null and true and back.
Exercise
A service returns the text '{"count": 3, "ratio": 2.0, "ok": false, "items": null}'. After json.loads, what are the Python types of the four values, and what would json.loads("2") return compared with json.loads("2.0")?
Show answer
count is int, ratio is float, ok is bool (False), and items is NoneType (None). json.loads("2") returns the int 2, and json.loads("2.0") returns the float 2.0. The decoder chooses the type from the text, so a fraction or exponent in the number makes it a float.
Exercise
Why might json.dumps({"score": float("inf")}) cause a problem for a program written in another language, and how do you make Python refuse to produce it?
Show answer
By default Python writes Infinity, which is not valid JSON, so a strict parser in another language can reject the whole document. Passing allow_nan=False makes json.dumps raise a ValueError instead, so the problem is caught on the Python side.