indusai.co

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

output
{
  "name": "Aditi",
  "age": 22,
  "skills": ["python", "sql"],
  "active": true,
  "manager": null
}
JSONPython
object {}dict
array []list
stringstr
numberint or float
true / falseTrue / False
nullNone

Parsing JSON text

json.loads (load string) converts JSON text into Python objects.

python
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.

python
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.

python
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.

python
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

python
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:

python
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

  1. Build a dictionary describing a book and save it to book.json with indentation. Open the file in a text editor to check it.
  2. Parse the nested example above and print the name of the student with the highest average.
  3. Load book.json back, change the year, and save it again.