JSON Files with the json Module
20 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)JSON is the text format that web services and apps use to exchange data. It looks almost like Python dictionaries and lists. The json module converts between JSON text and Python objects, so nested data can be saved and sent.
dumps and loads
JSON is a text format for data made of objects, lists, strings, numbers, true, false and null. Python maps these to dict, list, str, int or float, True, False and None.
Data in a program is a dictionary. Data on disk or on the network is text. json.dumps turns Python data into JSON text. json.loads turns JSON text back into Python data.
import json
student = {"name": "Asha", "marks": [82, 90], "passed": True, "badge": None}text = json.dumps(student)print(text)
back = json.loads(text)print(back["marks"][1], back["passed"], back["badge"])Example 1 · Dictionary to JSON and back
import json
student = {"name": "Asha", "marks": [82, 90], "passed": True, "badge": None}text = json.dumps(student)print(text)print(json.loads(text)["marks"]){"name": "Asha", "marks": [82, 90], "passed": true, "badge": null}
[82, 90]What this code does
TruebecametrueandNonebecamenullin the text.loadsrebuilds the dictionary, so["marks"]gives the list.
JSON writes True as true and None as null, with double quotes on every key and string. loads turns them back into True and None. The s in both names stands for string.
Save and load a JSON file
To keep data between runs, write it to a file. json.dump writes to an open file, and json.load reads from one. These two have no s because they work with files.
import json
orders = [{"id": 1, "amount": 250.5}, {"id": 2, "amount": 99}]with open("orders.json", "w", encoding="utf-8") as f: json.dump(orders, f)
with open("orders.json", encoding="utf-8") as f: loaded = json.load(f)print(loaded == orders)print(loaded[0]["amount"])Example 2 · Order list saved to a file
import json
orders = [{"id": 1, "amount": 250.5}, {"id": 2, "amount": 99}]with open("orders.json", "w") as f: json.dump(orders, f)with open("orders.json") as f: loaded = json.load(f)print(len(loaded), loaded[0]["amount"])print(loaded == orders)2 250.5 True
What this code does
dumpandloadwork with the file object.- The loaded data equals the data that was saved.
The loaded list equals the original, so nothing was lost. Remember: dump and load use a file object, dumps and loads use a string.
Pretty print, sort and key types
Compact JSON is hard to read. indent adds line breaks and spaces, and sort_keys puts the keys in order. Note that JSON keys are always text, so a number key comes back as a string.
import json
data = {"b": 2, "a": 1, "c": {"x": [1, 2]}}print(json.dumps(data, indent=2, sort_keys=True))
numbered = json.loads(json.dumps({1: "one"}))print(numbered)Example 3 · Readable output
import json
report = {"total": 3, "items": ["pen", "book"]}print(json.dumps(report, indent=2, sort_keys=True)){
"items": [
"pen",
"book"
],
"total": 3
}What this code does
indent=2puts each item on its own line.sort_keys=Truelistsitemsbeforetotal.
With indent=2 each level moves two spaces. sort_keys=True makes the output the same every time. The key 1 went out as "1" and came back as the string '1'.
Invalid JSON
JSONDecodeError is the error json.loads or json.load raises when the text is not valid JSON. It is a subclass of ValueError.
Text from outside can be broken, for example with single quotes or a missing bracket. json.loads raises json.JSONDecodeError, a kind of ValueError. Catch it and report the problem.
import json
def parse(text): try: return json.loads(text) except json.JSONDecodeError: return None
print(parse('{"id": 1}'))print(parse("{'id': 1}"))Example 4 · Bad JSON is caught
import json
for text in ['{"id": 1}', "{'id': 1}"]: try: print("ok", json.loads(text)) except json.JSONDecodeError: print("invalid JSON")ok {'id': 1}
invalid JSONWhat this code does
- The first text is valid, so it prints the dictionary.
- Single quotes are not valid JSON, so the except block runs.
JSON needs double quotes, so the second text is invalid and the function returns None. A real program would show a message or ask for the data again.
Next step
Check your understanding
10 quick questions