JSON text to Python
import json
text = '{"name": "Arta", "grade": 8, "subjects": ["maths", "art"], "captain": true, "phone": null}'
student = json.loads(text)
print(type(student))
print(student["name"], "is in grade", student["grade"])
print("Subjects:", ", ".join(student["subjects"]))
print(student["captain"], student["phone"])
json.loads ("load string") turns JSON text into Python values. JSON objects become dictionaries, arrays become lists, true/false become True/False, and null becomes None.
Python to JSON text
import json
result = {"student": "Dren", "score": 17, "out_of": 20, "passed": True, "notes": None}
print(json.dumps(result))
print(json.dumps(result, indent=2))
print(json.dumps({"city": "Durrës"}, ensure_ascii=False))
json.dumps ("dump string") does the reverse. indent=2 makes it readable for people, and ensure_ascii=False keeps letters like ë and ç as they are instead of turning them into codes such as ë.
Saving and loading files
import json
scores = [{"name": "Arta", "score": 92}, {"name": "Bora", "score": 78}]
with open("scores.json", "w", encoding="utf-8") as f:
json.dump(scores, f, indent=2)
with open("scores.json", encoding="utf-8") as f:
loaded = json.load(f)
loaded.append({"name": "Leon", "score": 85})
best = max(loaded, key=lambda s: s["score"])
print(len(loaded), "students, best:", best["name"])
Without the "s", json.dump and json.load work with files directly. Always pass encoding="utf-8", so names with special letters are saved correctly on every computer.
Missing keys and invalid JSON
import json
record = json.loads('{"name": "Ina"}')
print(record.get("grade", "unknown"))
for text in ['{"ok": true}', "{'ok': true}", '{"ok": true,}']:
try:
print(json.loads(text))
except json.JSONDecodeError as error:
print("Invalid JSON:", error.msg)
.get(key, default)returns a default instead of raisingKeyErrorwhen a field is missing, which is common in data from APIs.- JSON is stricter than Python: keys and strings need double quotes, and a trailing comma is not allowed.
Nested data
import json
data = json.loads('''
{
"school": "Unays Demo School",
"classes": [
{"name": "8A", "students": [{"name": "Arta", "score": 92}, {"name": "Ina", "score": 54}]},
{"name": "8B", "students": [{"name": "Dren", "score": 67}]}
]
}
''')
for cls in data["classes"]:
scores = [s["score"] for s in cls["students"]]
print(cls["name"], "average", round(sum(scores) / len(scores), 1))
Read nested data one level at a time: data["classes"] is a list, each item is a dictionary, and its "students" is another list. Printing a piece with json.dumps(..., indent=2) helps when you are lost.
Try it yourself
In Unays Code, build a small "reading log": a list of books as dictionaries, saved to books.json, loaded again, with a new book added and the total pages printed. To learn what produces JSON like this on the web, read what is an API?
This tutorial was written with AI assistance and reviewed by Unays. The runnable code examples were tested before publishing. Spotted a mistake? Tell us at [email protected].