JSON
JSON is a text format for objects, arrays, strings, numbers, booleans, and null. Python's json module converts between that text and dicts, lists, strs, ints, floats, bools, and None.
Detailed Explanation
json.dumps serialises a Python object to a string. json.loads parses a string. dump / load talk to files. The default encoder accepts dicts with string keys, lists, tuples (as arrays), str, int, float, True/False/None. It does not accept datetime, bytes, set, or dataclass instances unless you provide default= or a custom JSONEncoder.
Parsing does not validate your schema. loads('{"cents": "2500"}') succeeds and gives you a string. Validate with Pydantic, jsonschema, or hand-written checks at the HTTP boundary. TypedDict documents the shape for checkers; it does not run at runtime.
Numbers are a trap. JSON has one number type. json.loads("1e308") may become inf. Large integers that fit in Python int may lose precision if they passed through a float. Money should be integers (cents) or strings, not floats.
Keys become str. A Python dict with an int key will have string keys after a dump/load round trip if you used a non-default encoder, and dumps will refuse non-string keys by default (TypeError). sort_keys and separators make stable output for hashing. ensure_ascii=False keeps Unicode as characters, which is what you want for APIs.
Never json.loads untrusted text without a size cap. A huge nested array can exhaust memory. FastAPI and Flask parse for you and still need max body size at the proxy.
orjson and ujson are faster drop-ins with slightly different behaviours (datetime, strictness). The stdlib json is the portable default.
Code Examples
import json
from datetime import date
class Encoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, date):
return o.isoformat()
return super().default(o)
payload = {"sku": "A-1", "when": date(2026, 4, 1)}
text = json.dumps(payload, cls=Encoder)
print(text) # {"sku": "A-1", "when": "2026-04-01"}
print(json.loads(text)["sku"]) # A-1# Money as cents, not float.
print(json.dumps({"cents": 2500}))
# json.dumps({1: "a"}) # TypeError: keys must be strCommon Gotchas
`float` money
`0.1 + 0.2` and JSON numbers will hurt you. Use integer cents.
Loading without a schema
a missing key is a `KeyError` later, not a parse error. Validate at the edge.
`default=str` hides type bugs
everything becomes a string and the client cannot tell.
`NaN` and `Infinity` are not standard JSON
the stdlib allows them by default. `allow_nan=False` for strict APIs.