Lesson 5 of 6 · Modules and the Standard Library · 2 min read · Updated
Saving data as JSON
Turning dictionaries and lists into text you can store, and reading them back.
A file holds text, but your data lives in dictionaries and lists. JSON is a text format that maps almost exactly onto them, and the json module converts in both directions.
import json
student = {"name": "Priya", "marks": [87, 92], "active": True, "phone": None}
text = json.dumps(student)
print(text)
back = json.loads(text)
print(back["marks"][1], back["phone"])
{"name": "Priya", "marks": [87, 92], "active": true, "phone": null}
92 None
dumps turns data into a JSON string; loads turns a string back into data ("s" for string). Python's True and None become JSON's true and null, and back again.
To and from a file
import json
student = {"name": "Priya", "marks": [87, 92]}
with open("student.json", "w", encoding="utf-8") as f:
json.dump(student, f, indent=2)
with open("student.json", encoding="utf-8") as f:
loaded = json.load(f)
print(loaded == student)
print(json.dumps({"city": "மதுரை"}, ensure_ascii=False))
True
{"city": "மதுரை"}
dump/load(no s) work with an open file.indent=2writes readable, indented JSON.ensure_ascii=Falsekeeps Tamil as Tamil instead of\u0baecodes.
import json
print(json.loads(json.dumps({1: (2, 3)})))
{'1': [2, 3]}
Warning
The round trip is not perfect. JSON keys are always strings, so the key 1 comes back as "1"; tuples come back as lists; sets and dates cannot be saved at all without converting them first.
What does json.dumps(None) produce?
Try this now
- Keep a to-do list in todo.json: load it at start (or start empty if the file is missing), let the user add items, and save it at the end.
- Save a dictionary of Tamil words and their English meanings with ensure_ascii=False, then open the file and read it.
Create a free account to save your progress, or sign in.