Skip to content
IT Vizag
← Files, Modules & Packages

JSON: data for the web

Lesson 3 of 10 · 2 min read

Save and load structured data, as APIs do.

🎬 Video version coming soon — read it now

JSON (JavaScript Object Notation) is the format the web uses to send data. Web APIs, AI model responses and app settings files are almost always JSON. It looks very much like Python dictionaries and lists:

{
  "name": "Kavya",
  "skills": ["Python", "SQL"],
  "fresher": true,
  "cgpa": 8.7
}

Python ↔ JSON

The built-in json module converts between the two:

import json

profile = {"name": "Kavya", "skills": ["Python", "SQL"], "fresher": True, "cgpa": 8.7}

text = json.dumps(profile, indent=2)   # Python → JSON text
print(text)

back = json.loads(text)                # JSON text → Python
print(back["skills"][0])               # Python

Remember: dumps = dump to a string, loads = load from a string.

Saving and loading files

import json

with open("profile.json", "w", encoding="utf-8") as f:
    json.dump(profile, f, indent=2, ensure_ascii=False)

with open("profile.json", encoding="utf-8") as f:
    loaded = json.load(f)

ensure_ascii=False keeps Telugu and other scripts readable in the file instead of turning them into codes.

Small differences to know

  • JSON uses true, false and null; Python uses True, False and None. The module converts them.
  • JSON keys must be strings. A dictionary with number keys comes back with string keys.
  • Tuples become lists, and sets can't be saved at all. Convert them to lists first.

JSON vs CSV

  • CSV: flat tables, every row the same columns. Opens in Excel.
  • JSON: nested data: lists inside dictionaries inside lists. Used by APIs and apps.

Reading nested JSON

order = json.loads('{"id": 101, "items": [{"name": "Dosa", "qty": 2}, {"name": "Tea", "qty": 1}]}')
for item in order["items"]:
    print(item["name"], item["qty"])

When you call AI models from Python in the Python Meets AI course, the answers come back in exactly this kind of structure.

Tip: To explore an unfamiliar JSON response, print it with json.dumps(data, indent=2). The indentation makes the structure obvious.

In one line

json.dumps/loads convert Python to JSON text and back, json.dump/load do the same with files, and it's the language of web APIs.

Saved on this device. Sign in to keep progress everywhere.

Share with a friend