Python JSON Examples
Short, runnable programs that show working with json in python in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Working with JSON in Python lesson.
1Save and load a JSON file
json.dump() writes Python data to a file as JSON, and json.load() reads it back as an equal dict — the simplest way to keep data between runs.
import json
settings = {"theme": "dark", "font_size": 14, "autosave": True, "recent": ["notes.txt", "todo.txt"]}
with open("settings.json", "w") as f:
json.dump(settings, f, indent=2)
with open("settings.json") as f:
print(f.read())
with open("settings.json") as f:
loaded = json.load(f)
print(loaded == settings, loaded["recent"][0])Expected output{
"theme": "dark",
"font_size": 14,
"autosave": true,
"recent": [
"notes.txt",
"todo.txt"
]
}
True notes.txt
2Formatting options for dumps()
By default non-ASCII characters are escaped as \u codes. sort_keys=True orders the keys and ensure_ascii=False keeps characters such as é readable.
import json
place = {"name": "Café Mila", "rating": 4.5, "city": "Lyon"}
print(json.dumps(place))
print(json.dumps(place, sort_keys=True))
print(json.dumps(place, ensure_ascii=False))Expected output{"name": "Caf\u00e9 Mila", "rating": 4.5, "city": "Lyon"}
{"city": "Lyon", "name": "Caf\u00e9 Mila", "rating": 4.5}
{"name": "Café Mila", "rating": 4.5, "city": "Lyon"}
3Loop over a JSON array of records
APIs often return a list of objects. After json.loads() it is just a list of dicts, so comprehensions and loops work as usual.
import json
todos_json = '''[
{"id": 1, "title": "Buy milk", "completed": false},
{"id": 2, "title": "Pay rent", "completed": true},
{"id": 3, "title": "Call mum", "completed": false}
]'''
todos = json.loads(todos_json)
pending = [todo["title"] for todo in todos if not todo["completed"]]
print(f"{len(pending)} of {len(todos)} tasks pending:")
for title in pending:
print("-", title)Expected output2 of 3 tasks pending:
- Buy milk
- Call mum
4Catch invalid JSON
json.JSONDecodeError tells you what went wrong. Catch it when the text comes from a user, a file or the internet.
import json
samples = ['{"ok": true}', "{'ok': true}", '{"ok": true,}']
for text in samples:
try:
print("Parsed:", json.loads(text))
except json.JSONDecodeError as err:
print("Invalid JSON:", err.msg)Expected outputParsed: {'ok': True}
Invalid JSON: Expecting property name enclosed in double quotes
Invalid JSON: Illegal trailing comma before end of object
Practise next
Working with JSON in Python exercises → Back to the lesson
Python Dictionaries examplesPython CSV Files examplesPython requests: Call Web APIs examplesPython API Example: Build an API Client examples