Working with JSON in Python
Python's standard library includes the json module, so you can read and write JSON without installing anything. This guide covers the four functions you'll use every day, how Python types map to JSON, and fixes for the errors beginners hit most often.
The four functions: loads, dumps, load, dump
The names are easy to mix up. The s stands for string: functions ending in s work with strings, and the others work with files.
| From/to a string | From/to a file | |
|---|---|---|
| Read JSON into Python | json.loads(text) | json.load(file) |
| Write Python as JSON | json.dumps(data) | json.dump(data, file) |
import json
# String -> Python
user = json.loads('{"name": "Ada", "skills": ["math", "poetry"], "active": true}')
print(user["skills"][0]) # math
# Python -> string
text = json.dumps({"name": "Ada", "active": True})
print(text) # {"name": "Ada", "active": true}
# File -> Python
with open("config.json", encoding="utf-8") as f:
config = json.load(f)
# Python -> file
with open("output.json", "w", encoding="utf-8") as f:
json.dump(config, f, indent=2)Always pass encoding="utf-8" when opening JSON files. JSON is defined as UTF-8, but Python's default encoding depends on your operating system, and on Windows it often isn't UTF-8.
How Python types map to JSON
| Python | JSON | Notes |
|---|---|---|
dict | object | Non-string keys are converted: {1: "a"} becomes {"1": "a"} |
list, tuple | array | Tuples come back as lists when you load the JSON |
str | string | |
int, float | number | Python keeps big integers exact; JavaScript may not |
True, False | true, false | Lowercase in JSON |
None | null |
A dict isn't JSON
A Python dictionary printed with print(data) looks like JSON but isn't: it uses single quotes, True and None. If you need JSON to paste somewhere, print json.dumps(data) instead. Pasting a printed dictionary is the top cause of the single quotes error.
Pretty printing and sorting keys
json.dumps puts everything on one line by default. Add indent for readable output and sort_keys=True for a stable key order, which makes files easier to compare in version control:
print(json.dumps({"b": 1, "a": [1, 2]}, indent=2, sort_keys=True)){
"a": [
1,
2
],
"b": 1
}For the smallest possible output, remove the spaces Python adds after separators: json.dumps(data, separators=(",", ":")). You can also format a file without writing any code: python3 -m json.tool data.json. The formatting guide lists its options.
Non-English text and emoji
By default, json.dumps escapes every non-ASCII character:
json.dumps({"city": "Zürich"}) # {"city": "Z\u00fcrich"}
json.dumps({"city": "Zürich"}, ensure_ascii=False) # {"city": "Zürich"}Both are valid JSON and load back to the same string. Use ensure_ascii=False when people will read the output, and make sure the file is opened with encoding="utf-8" when you do.
"Object of type ... is not JSON serializable"
json.dumps only knows the types in the table above. Anything else raises a TypeError:
from datetime import datetime
json.dumps({"when": datetime(2026, 12, 5, 10, 0)})
# TypeError: Object of type datetime is not JSON serializableYou'll see the same message for set, Decimal, UUID, NumPy numbers and your own classes. The fix is a default function, which json.dumps calls for any object it can't handle. Whatever it returns is used instead:
from datetime import date, datetime
from decimal import Decimal
def to_json(value):
if isinstance(value, (datetime, date)):
return value.isoformat() # "2026-12-05T10:00:00"
if isinstance(value, set):
return sorted(value)
if isinstance(value, Decimal):
return str(value) # keep the exact digits
raise TypeError(f"Can't convert {type(value).__name__} to JSON")
json.dumps({"when": datetime(2026, 12, 5, 10, 0), "tags": {"b", "a"}}, default=to_json)
# {"when": "2026-12-05T10:00:00", "tags": ["a", "b"]}A quick shortcut is default=str, which turns anything unknown into its string form. It's fine for logging, but be deliberate in real APIs: str() of a datetime gives "2026-12-05 10:00:00" with a space, not the ISO 8601 format most other systems expect.
The NaN trap
Python's json module happily writes NaN, Infinity and -Infinity, even though they aren't valid JSON:
json.dumps({"score": float("nan")}) # {"score": NaN} <- not valid JSONPython can read that back, but a browser or another language will reject it. This typically shows up after a Pandas or NumPy calculation with missing data. Pass allow_nan=False to get an error instead of invalid output, and replace missing values with None before saving:
json.dumps({"score": float("nan")}, allow_nan=False)
# ValueError: Out of range float values are not JSON compliant: nanErrors when reading JSON
When the text isn't valid JSON, json.loads and json.load raise json.JSONDecodeError. It has lineno, colno and pos attributes, so you can report exactly where the problem is:
try:
data = json.loads(text)
except json.JSONDecodeError as e:
print(f"Invalid JSON at line {e.lineno}, column {e.colno}: {e.msg}")What JSON error messages mean has a table of every common message and its cause. The one beginners see most is Expecting value: line 1 column 1 (char 0), which means the text is empty or isn't JSON at all, often an HTML error page from a web request.
JSON from web APIs with requests
The popular requests library (installed with pip install requests) parses JSON responses for you with .json(), and sends Python data as JSON with the json= argument, setting the Content-Type header for you:
import requests
response = requests.get("https://api.example.com/orders", timeout=10)
response.raise_for_status() # raise an error for 4xx/5xx instead of parsing an error page
orders = response.json()
requests.post("https://api.example.com/orders", json={"sku": "MUG-01", "qty": 2}, timeout=10)Calling raise_for_status() before .json() means a failed request gives you a clear HTTP error instead of a confusing JSONDecodeError.