Working with JSON
JSON is the standard text format for exchanging data between programs and over the web. Its structure maps almost one to one onto Python dictionaries and lists, so converting between them is a single function call.
What JSON looks like
{
"name": "Aditi",
"age": 22,
"skills": ["python", "sql"],
"active": true,
"manager": null
}| JSON | Python |
|---|---|
object {} | dict |
array [] | list |
| string | str |
| number | int or float |
true / false | True / False |
null | None |
Parsing JSON text
json.loads (load string) converts JSON text into Python objects.
import json
text = '{"name": "Aditi", "age": 22, "skills": ["python", "sql"], "manager": null}'
data = json.loads(text)
print(type(data))
print(data["name"], data["skills"][0], data["manager"])Producing JSON text
json.dumps (dump string) does the reverse.
import json
profile = {"name": "Aditi", "age": 22, "skills": ["python", "sql"], "active": True}
print(json.dumps(profile))
print(json.dumps(profile, indent=2))
print(json.dumps(profile, indent=2, sort_keys=True))indent makes the output readable. ensure_ascii=False keeps non English characters as they are instead of escaping them.
Reading and writing files
json.load and json.dump (no "s") work on file objects.
import json
records = [{"id": 1, "city": "Surat"}, {"id": 2, "city": "Indore"}]
with open("records.json", "w") as f:
json.dump(records, f, indent=2)
with open("records.json") as f:
loaded = json.load(f)
print(loaded[1]["city"])Nested data
Walk it exactly like nested dictionaries and lists.
import json
text = '''
{
"course": "ML",
"students": [
{"name": "Ira", "marks": [88, 92]},
{"name": "Jay", "marks": [75, 81]}
]
}
'''
data = json.loads(text)
for s in data["students"]:
print(s["name"], sum(s["marks"]) / len(s["marks"]))Invalid JSON
import json
try:
json.loads("{'single': 'quotes'}")
except json.JSONDecodeError as e:
print("Bad JSON:", e)JSON requires double quotes, no trailing commas and no comments.
Types JSON cannot represent
Dates, sets, tuples and custom objects are not JSON. Convert them first, or pass a default function:
import json
from datetime import date
payload = {"when": date(2026, 9, 15), "tags": {"a", "b"}}
print(json.dumps(payload, default=lambda o: str(o) if isinstance(o, date) else sorted(o)))Practice
- Build a dictionary describing a book and save it to
book.jsonwith indentation. Open the file in a text editor to check it. - Parse the nested example above and print the name of the student with the highest average.
- Load
book.jsonback, change the year, and save it again.
