TExcelTAD
Home › JSON › JSON in Python

JSON in Python

Python ships with the json module in its standard library, so you can read and write JSON without installing anything. The module's API is small: four functions plus a few options.

Function Converts Mnemonic
json.loads(text) JSON string → Python object load string
json.dumps(obj) Python object → JSON string dump string
json.load(file) JSON file → Python object
json.dump(obj, file) Python object → JSON file

Type mapping

JSON Python (when loading) Python types that dump to it
object dict dict
array list list, tuple
string str str
number (int) int int
number (real) float float
true / false True / False bool
null None None

Parsing with loads()

python · try it yourself
import json

text = '''
{
  "library": "City Library",
  "open": true,
  "books": [
    {"title": "Rivers", "year": 2019, "loaned": false},
    {"title": "Mountains", "year": 2021, "loaned": true}
  ],
  "director": null
}
'''

data = json.loads(text)
print(type(data), type(data["books"]))
print(data["open"], data["director"])

for book in data["books"]:
    status = "on loan" if book["loaned"] else "available"
    print(f"{book['title']} ({book['year']}): {status}")
<class 'dict'> <class 'list'>
True None
Rivers (2019): available
Mountains (2021): on loan

Serializing with dumps()

python · try it yourself
import json

profile = {
    "name": "Nam",
    "langs": ("python", "sql"),
    "active": True,
    "score": 9.5,
    "team": None,
    "city": "Hà Nội",
}

print(json.dumps(profile))
print(json.dumps(profile, indent=2, ensure_ascii=False, sort_keys=True))
print(json.dumps(profile, separators=(",", ":"), ensure_ascii=False))
{"name": "Nam", "langs": ["python", "sql"], "active": true, "score": 9.5, "team": null, "city": "H\u00e0 N\u1ed9i"}
{
  "active": true,
  "city": "Hà Nội",
  "langs": [
    "python",
    "sql"
  ],
  "name": "Nam",
  "score": 9.5,
  "team": null
}
{"name":"Nam","langs":["python","sql"],"active":true,"score":9.5,"team":null,"city":"Hà Nội"}

Useful options of dumps() / dump():

Option Effect
indent=2 Pretty print with 2-space indentation
sort_keys=True Sort object keys alphabetically
ensure_ascii=False Keep characters like à instead of à
separators=(",", ":") Most compact output
default=func Called for objects the module doesn't know

Errors when parsing

Invalid input raises json.JSONDecodeError, which carries the message, line and column:

python · try it yourself
import json

broken = '{"a": 1,\n "b": [1, 2,]\n}'
try:
    json.loads(broken)
except json.JSONDecodeError as err:
    print("Message:", err.msg)
    print("Line:", err.lineno, "Column:", err.colno)
Message: Illegal trailing comma before end of array
Line: 2 Column: 12

Python 3.13 names the problem directly (Illegal trailing comma before end of array) and points at the comma itself. Older versions said Expecting value and pointed one character later, at the ]. Every parser words errors differently, but the line and column always lead you to the problem.

Note: Python's parser is a little more lenient than JavaScript's by default: it accepts NaN, Infinity and -Infinity. And json.dumps(float("nan")) writes NaN, which is not valid JSON — pass allow_nan=False to get an error instead.

Custom objects: default and object_hook

dumps can't serialize your own classes, dates or sets by itself. Supply a default function to convert them. In the other direction, object_hook is called for every decoded object, letting you build class instances:

python · try it yourself
import json
from dataclasses import dataclass, asdict

@dataclass
class Product:
    sku: str
    price: float

items = [Product("TEA-1", 4.5), Product("CUP-2", 3.0)]

def encode(obj):
    if isinstance(obj, Product):
        return {"__type__": "Product", **asdict(obj)}
    raise TypeError(f"Can't encode {type(obj).__name__}")

text = json.dumps(items, default=encode)
print(text)

def decode(d):
    if d.get("__type__") == "Product":
        return Product(d["sku"], d["price"])
    return d

back = json.loads(text, object_hook=decode)
print(back)
print(back == items)
[{"__type__": "Product", "sku": "TEA-1", "price": 4.5}, {"__type__": "Product", "sku": "CUP-2", "price": 3.0}]
[Product(sku='TEA-1', price=4.5), Product(sku='CUP-2', price=3.0)]
True

Files

Reading and writing files uses load() and dump() with an open file. Always specify UTF-8:

python
import json

with open("config.json", "w", encoding="utf-8") as f:
    json.dump({"debug": False, "port": 8000}, f, indent=2)

with open("config.json", encoding="utf-8") as f:
    config = json.load(f)

Gotcha: keys become strings

JSON object keys are always strings, so non-string dict keys don't survive a round trip:

python · try it yourself
import json

counts = {1: "one", 2: "two"}
text = json.dumps(counts)
print(text)
print(json.loads(text))
print(json.loads(text) == counts)
{"1": "one", "2": "two"}
{'1': 'one', '2': 'two'}
False

Command line

Python includes a quick validator and pretty printer:

bash
python3 -m json.tool data.json
echo '{"b": 1, "a": [1,2]}' | python3 -m json.tool --sort-keys

Test yourself

Which function reads JSON from an open file object?

  1. json.loads()
  2. json.load()
  3. json.read()
  4. json.parse()

What does JSON null become in Python?

  1. null
  2. 0
  3. None
  4. ""

What happens to the dict {1: "a"} after json.loads(json.dumps(...))?

  1. It stays {1: 'a'}
  2. It becomes {'1': 'a'}
  3. It raises TypeError
  4. It becomes ['a']