Python course menu
Python JSON: Read, Write and Parse JSON Data
Learn to work with JSON in Python: convert dictionaries to JSON with dumps, parse JSON strings with loads, read and write JSON files with dump and load, navigate nested API data, and handle common JSON errors.
On this page
JSON (JavaScript Object Notation) is the most common format for exchanging data between programs: web APIs, configuration files, and many databases use it. JSON looks almost exactly like Python dictionaries and lists, and the built-in json module converts between the two.
JSON and Python side by side#
Python to JSON text: dumps#
json.dumps() ("dump string") turns Python data into a JSON string:
import json
student = {"name": "Asha", "age": 21, "skills": ["python", "sql"],
"active": True, "mentor": None}
text = json.dumps(student)
print(text)
print(type(text).__name__){"name": "Asha", "age": 21, "skills": ["python", "sql"], "active": true, "mentor": null}
strNotice True became true and None became null. Add indent for readable output:
print(json.dumps({"name": "Asha", "age": 21, "skills": ["python", "sql"]}, indent=2)){
"name": "Asha",
"age": 21,
"skills": [
"python",
"sql"
]
}JSON text to Python: loads#
json.loads() ("load string") parses JSON text into Python objects:
text = '{"name": "Ravi", "age": 25, "active": false, "scores": [85, 90]}'
data = json.loads(text)
print(data["name"], data["active"], sum(data["scores"]))
print(type(data).__name__)Ravi False 175
dictAfter parsing, it is an ordinary dictionary: index it, loop over it, change it.
Reading and writing JSON files#
json.dump() and json.load() (no "s") work with files directly:
settings = {"theme": "dark", "font_size": 14, "languages": ["en", "hi"]}
with open("settings.json", "w", encoding="utf-8") as f:
json.dump(settings, f, indent=2)
with open("settings.json", encoding="utf-8") as f:
loaded = json.load(f)
print(loaded == settings, loaded["languages"])True ['en', 'hi']Navigating nested JSON#
API responses are usually nested. Work from the outside in:
response = '''{
"user": {"id": 7, "name": "Meera"},
"orders": [
{"id": 101, "total": 250},
{"id": 102, "total": 120}
]
}'''
data = json.loads(response)
print(data["user"]["name"])
print([o["id"] for o in data["orders"]])
print(sum(o["total"] for o in data["orders"]))Meera
[101, 102]
370Non-English text#
By default, non-ASCII characters are escaped. Pass ensure_ascii=False to keep them readable:
print(json.dumps({"city": "पुणे"}), json.dumps({"city": "पुणे"}, ensure_ascii=False)){"city": "\u092a\u0941\u0923\u0947"} {"city": "पुणे"}Both are valid JSON and load back to the same string.
Common errors#
Invalid JSON. JSON is stricter than Python: keys and strings need double quotes, and trailing commas are not allowed.
json.loads("{'name': 'Asha'}")json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)Catch json.JSONDecodeError when parsing data you do not control. The JSON Formatter tool can show you exactly where a JSON document is broken.
Types JSON does not support. Dates, sets and custom objects cannot be converted automatically:
from datetime import date
json.dumps({"day": date(2026, 10, 23)})TypeError: Object of type date is not JSON serializableThe quickest fix is default=str, which converts unknown objects to strings:
print(json.dumps({"day": date(2026, 10, 23)}, default=str)){"day": "2026-10-23"}Common mistakes#
Practice#
Practice exercise
Parse the response JSON from the "Navigating nested JSON" section and print a line for each order like Order 101: ₹250, followed by Meera spent ₹370.
Show hint
Loop over data["orders"]; use data["user"]["name"] and sum(...) for the last line.
Show solution
import json
data = json.loads(response)
for order in data["orders"]:
print(f"Order {order['id']}: ₹{order['total']}")
total = sum(o["total"] for o in data["orders"])
print(f"{data['user']['name']} spent ₹{total}")Order 101: ₹250
Order 102: ₹120
Meera spent ₹370Inside an f-string that uses double quotes, use single quotes for the dictionary keys.
Key takeaway#
Finished this lesson?