{}JSON FYI

How to read and write JSON files in Python

Complete guide to Python's json module: json.load(), json.loads(), json.dump(), json.dumps(), and common errors — with real-world examples.

·6 min read

Python's built-in json module handles all JSON serialization and deserialization. No third-party packages are needed for standard JSON work.

Reading JSON from a string

import json

raw = '{"name": "Ada", "age": 30, "active": true}'
data = json.loads(raw)   # loads = load string

print(data["name"])   # Ada
print(data["age"])    # 30
print(type(data))     # <class 'dict'>

Reading a JSON file

import json

with open("data.json", encoding="utf-8") as f:
    data = json.load(f)   # load (no 's') reads from a file object

print(data)              # Python dict or list

Always specify encoding='utf-8' to avoid platform-dependent encoding issues, especially on Windows.

Writing JSON to a string

import json

data = {"name": "Ada", "scores": [98, 87, 95], "active": True}

compact = json.dumps(data)
# '{"name": "Ada", "scores": [98, 87, 95], "active": true}'

pretty = json.dumps(data, indent=2)
# {
#   "name": "Ada",
#   "scores": [98, 87, 95],
#   "active": true
# }

Writing a JSON file

import json

data = {"name": "Ada", "age": 30}

with open("output.json", "w", encoding="utf-8") as f:
    json.dump(data, f, indent=2)   # dump (no 's') writes to a file object

Handling JSONDecodeError

import json

def safe_parse(text: str):
    try:
        return json.loads(text)
    except json.JSONDecodeError as e:
        print(f"Invalid JSON at line {e.lineno}, col {e.colno}: {e.msg}")
        return None

result = safe_parse('{"broken": }')
# Invalid JSON at line 1, col 12: Expecting value

Type mapping: JSON to Python

# JSON        → Python
# object       → dict
# array        → list
# string       → str
# number (int) → int
# number (float)→ float
# true         → True
# false        → False
# null         → None

Sorting keys and controlling output

json.dumps(data, sort_keys=True)           # alphabetical key order
json.dumps(data, indent=2, sort_keys=True) # pretty + sorted
json.dumps(data, ensure_ascii=False)       # allow non-ASCII chars (e.g. emoji, CJK)
json.dumps(data, separators=(',', ':'))    # compact, no spaces

Custom serialization with default

import json
from datetime import datetime, date

def json_default(obj):
    if isinstance(obj, (datetime, date)):
        return obj.isoformat()
    raise TypeError(f"Object of type {type(obj)} is not JSON serializable")

data = {"name": "Ada", "joined": datetime(2024, 1, 15)}
json.dumps(data, default=json_default)
# '{"name": "Ada", "joined": "2024-01-15T00:00:00"}'

Find the problem with the JSON linter →

The linter surfaces trailing commas, duplicate keys, and other common issues with line and column numbers.

Open JSON Linter →

Frequently asked questions

What is the difference between json.load() and json.loads()?+

json.load() reads from a file-like object (anything with a .read() method). json.loads() parses a string (or bytes). The 's' stands for 'string'.

How do I read a JSON file with UTF-8 encoding?+

Always pass encoding='utf-8' to open(): with open('file.json', encoding='utf-8') as f: data = json.load(f). Without it, Python uses the system default encoding which can vary by platform.

Can json.loads() parse a JSON array at the top level?+

Yes. json.loads('[1, 2, 3]') returns the Python list [1, 2, 3]. Any valid JSON value is accepted.

How do I pretty-print JSON in Python?+

Use json.dumps(data, indent=2) for a formatted string, or print(json.dumps(data, indent=2)) to output it. To pretty-print a file in the terminal: python -m json.tool data.json

Related tools & guides