Python JSON Guide: load, dumps and Fixing Common Errors
Python’s built-in json module covers almost everything you need: reading and writing files, converting strings, and pretty printing. This guide covers the four main functions, the errors you will meet (with their real messages), and how to handle dates, decimals and other types the module can’t serialize on its own. Examples were run on Python 3.9 and behave the same on newer versions.
The four functions
| Function | From → to |
|---|---|
json.load(f) | file → Python object |
json.loads(s) | string → Python object (the “s” is for string) |
json.dump(obj, f) | Python object → file |
json.dumps(obj) | Python object → string |
import json
# read a file
with open("data.json", encoding="utf-8") as f:
data = json.load(f)
# write a file – readable and keeping non-English characters as they are
with open("out.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
# strings
obj = json.loads('{"name": "Ann", "tags": ["a", "b"]}')
text = json.dumps(obj)encoding="utf-8". On Windows, open() may default to another encoding and fail on characters like é or emoji.How types are converted
| Python | JSON |
|---|---|
| dict | object (keys become strings) |
| list, tuple | array |
| str | string |
| int, float | number |
| True / False / None | true / false / null |
>>> json.dumps({1: (1, 2)})
'{"1": [1, 2]}'
>>> json.loads(json.dumps({1: "x"}))
{'1': 'x'} # the int key came back as a stringPretty printing and compact output
>>> json.dumps({"name": "Zoë"})
'{"name": "Zo\\u00eb"}' # default: non-ASCII is escaped
>>> json.dumps({"name": "Zoë"}, ensure_ascii=False)
'{"name": "Zoë"}'
>>> print(json.dumps({"b": 1, "a": 2}, sort_keys=True, indent=2))
{
"a": 2,
"b": 1
}
>>> json.dumps({"a": [1, 2]}, separators=(",", ":")) # smallest output
'{"a":[1,2]}'From the terminal, Python ships a formatter and validator:
$ python3 -m json.tool --indent 2 data.json
$ echo '{"a":1,}' | python3 -m json.tool
Expecting property name enclosed in double quotes: line 1 column 8 (char 7)“Object of type datetime is not JSON serializable”
json only knows the basic types above. Dates, Decimal, set, UUID and your own classes all raise a TypeError:
>>> json.dumps({"at": datetime.datetime(2026, 11, 20, 9, 30)})
TypeError: Object of type datetime is not JSON serializable
>>> json.dumps({"s": {1, 2}})
TypeError: Object of type set is not JSON serializable
>>> json.dumps({"price": decimal.Decimal("9.99")})
TypeError: Object of type Decimal is not JSON serializableThe quick fix is default=str, which calls str() on anything unknown:
>>> json.dumps({"at": datetime.datetime(2026, 11, 20, 9, 30), "id": uuid.UUID(int=1)}, default=str)
'{"at": "2026-11-20 09:30:00", "id": "00000000-0000-0000-0000-000000000001"}'Notice the date: str() gives 2026-11-20 09:30:00 with a space, not the ISO 8601 format other systems expect. A small default function gives you full control:
import datetime, decimal
def to_json(o):
if isinstance(o, (datetime.date, datetime.datetime)):
return o.isoformat()
if isinstance(o, decimal.Decimal):
return str(o) # keep exact money values as strings
if isinstance(o, set):
return sorted(o)
raise TypeError(f"Object of type {type(o).__name__} is not JSON serializable")
json.dumps({"at": datetime.date(2026, 11, 20), "p": decimal.Decimal("9.99"), "s": {2, 1}}, default=to_json)
# '{"at": "2026-11-20", "p": "9.99", "s": [1, 2]}'JSONDecodeError: what each message means
| Input | Message | Real cause |
|---|---|---|
"" or <html> | Expecting value: line 1 column 1 (char 0) | Empty response, or an HTML error page instead of JSON |
{'a': 1} | Expecting property name enclosed in double quotes: line 1 column 2 | Single quotes – often a Python dict printed with str() |
{"a": 1,} | Expecting property name enclosed in double quotes: line 1 column 9 | Trailing comma |
{"a": True} | Expecting value: line 1 column 7 | Python True/None instead of true/null |
The error object tells you exactly where the problem is:
try:
data = json.loads(text)
except json.JSONDecodeError as e:
print(e.msg, "at line", e.lineno, "column", e.colno)
print(text[max(0, e.pos - 30):e.pos + 30]) # show the text around itstr(my_dict) is not JSON: it prints {'ok': True, 'n': None}. Use json.dumps whenever the text will be read by another program. If you already have a file full of Python-style dicts, JSON Repair converts quotes, True/False/None and trailing commas for you.With requests, “Expecting value: line 1 column 1” almost always means the server didn’t return JSON. Check response.status_code and response.text[:200] before calling response.json().
Surprises worth knowing
>>> json.dumps({"x": float("nan"), "y": float("inf")})
'{"x": NaN, "y": Infinity}' # NOT valid JSON – other languages will reject it
>>> json.dumps({"x": float("nan")}, allow_nan=False)
ValueError: Out of range float values are not JSON compliant
>>> json.loads('{"a": 1, "a": 2}')
{'a': 2} # duplicate keys: the last one wins, silently
>>> json.loads('{"id": 12345678901234567890}')["id"]
12345678901234567890 # Python ints are exact; JavaScript would round this
>>> json.loads('{"p": 0.1}', parse_float=decimal.Decimal)
{'p': Decimal('0.1')} # exact decimals for moneyTo turn strings back into dates while loading, use object_hook:
json.loads('{"at": "2026-11-20"}',
object_hook=lambda d: {k: (datetime.date.fromisoformat(v) if k == "at" else v) for k, v in d.items()})
# {'at': datetime.date(2026, 11, 20)}Big files
json.load reads the whole file into memory – a 1 GB file can need several GB of RAM. For huge arrays, use a streaming parser such as ijson, or store the data as JSON Lines and process one line at a time. To just look inside a big file, the JSON Viewer opens 100 MB+ files in the browser.