PythonMastery
reference 5 min read · lesson 24 of 25 in Reference

Python JSON Cheat Sheet

1 · The lesson

read

JSON is a plain-text format for data that almost every language and web API can read. Python's json module turns JSON text into dicts and lists, and turns them back into text. For the full tutorial, see CSV and JSON. When something goes wrong, see JSONDecodeError and Object is not JSON serializable.

1. Text to Python and back

json.loads reads a JSON string and gives you Python data. json.dumps does the opposite: it turns Python data into a JSON string. The "s" at the end of both names stands for "string".

python
import json

text = '{"name": "Ada", "age": 36}'
person = json.loads(text)
print(person["name"])                        # Ada
print(json.dumps(person))                    # {"name": "Ada", "age": 36}
print(json.dumps([1, "two", None, True]))    # [1, "two", null, true]

2. How the types match

PythonJSON
dictobject {}
list, tuplearray []
strstring ""
int, floatnumber
True / Falsetrue / false
Nonenull

A tuple becomes an array, and an array always comes back as a list.

python
import json

print(json.dumps((1, 2)))         # [1, 2]
print(json.loads("[1, 2]"))       # [1, 2]

3. Pretty and sorted

indent puts each item on its own line, which is easier to read. sort_keys=True puts the keys in A to Z order. separators=(",", ":") removes the spaces, which gives the shortest text.

python
import json

order = {"item": "tea", "id": 7}
print(json.dumps(order, indent=2))
print(json.dumps(order, sort_keys=True))             # {"id": 7, "item": "tea"}
print(json.dumps(order, separators=(",", ":")))      # {"item":"tea","id":7}
python
{
  "item": "tea",
  "id": 7
}
{"id": 7, "item": "tea"}
{"item":"tea","id":7}

4. Files: dump and load

json.dump (no "s") writes to an open file. json.load reads from an open file. Use with open(...): it closes the file even if your code fails.

python
import json

orders = [{"name": "Grace", "total": 12.5}]
with open("orders.json", "w", encoding="utf-8") as f:
    json.dump(orders, f, indent=2)

with open("orders.json", encoding="utf-8") as f:
    data = json.load(f)
print(data)              # [{'name': 'Grace', 'total': 12.5}]
print(data == orders)    # True

5. Text in other languages

By default, any letter outside basic English is written as a \u code. The \u code is still valid JSON, but it is hard to read. ensure_ascii=False keeps the real letters. Open the file with encoding="utf-8" when you do this.

python
import json

print(json.dumps("café"))                      # "caf\u00e9"
print(json.dumps("café", ensure_ascii=False))  # "café"
print(json.loads('"caf\\u00e9"'))              # café

6. Dates, sets and other types

json only knows the types in the table above. For anything else, pass default=. Its value is a function, and json calls that function for each value it cannot write. str and list are common choices.

python
import json
from datetime import date

event = {"day": date(2026, 10, 24), "tags": {"vip"}}
try:
    json.dumps(event)
except TypeError as e:
    print("TypeError:", e)   # TypeError: Object of type date is not JSON serializable

print(json.dumps({"day": date(2026, 10, 24)}, default=str))   # {"day": "2026-10-24"}
print(json.dumps({"tags": {"vip"}}, default=list))           # {"tags": ["vip"]}

back = json.loads('{"day": "2026-10-24"}')
print(date.fromisoformat(back["day"]))   # 2026-10-24

The date comes back as a plain string, so turn it back into a date yourself.

7. Read nested data safely

Replies from web APIs are often dicts inside dicts. Use .get() when a key may be missing: .get() gives None or your default instead of a KeyError.

python
import json

data = json.loads('{"user": {"name": "Ada", "langs": ["py", "sql"]}}')
print(data["user"]["langs"][0])              # py
print(data["user"].get("email", "none"))     # none
print(data.get("order", {}).get("id"))       # None

8. Bad JSON

json.loads raises json.JSONDecodeError when the text is not valid JSON. The error tells you the line and column.

python
import json

text = '{"name": "Ada",}'
try:
    data = json.loads(text)
except json.JSONDecodeError as e:
    print("Bad JSON, line", e.lineno, "column", e.colno)   # Bad JSON, line 1 column 15

An empty string, such as an empty file or an empty web reply, also raises JSONDecodeError.

Common mistakes

Single quotes. A Python dict printed with print() is not JSON. JSON needs double quotes. Use json.dumps, not str(), to make JSON text.

python
import json

try:
    json.loads("{'a': 1}")
except json.JSONDecodeError:
    print("JSONDecodeError")         # JSONDecodeError
print(json.loads('{"a": 1}'))        # {'a': 1}

Keys always become strings. A number key 1 comes back as the string "1".

python
import json

scores = {1: "Hedy", 2: "Linus"}
back = json.loads(json.dumps(scores))
print(back)          # {'1': 'Hedy', '2': 'Linus'}
print(back["1"])     # Hedy

dump and dumps. json.dumps(data) gives a string. json.dump(data, f) writes to a file and needs the file. Calling json.dump(data) raises TypeError.

Trailing commas. Python allows a comma after the last item. JSON does not.

python
import json

try:
    json.loads("[1, 2,]")
except json.JSONDecodeError:
    print("JSONDecodeError")   # JSONDecodeError

NaN. json.dumps writes float("nan") as NaN, which is not valid JSON. Other programs may reject it. allow_nan=False makes Python raise an error instead.

python
import json

print(json.dumps(float("nan")))            # NaN
try:
    json.dumps(float("nan"), allow_nan=False)
except ValueError:
    print("ValueError")                     # ValueError

Found this useful? Share it with a friend who’s learning Python.