CodeMIRAI
0 XP

Working with JSON

2 min read 5 runnable examples Quiz included

JSON (JavaScript Object Notation) is the most common format for exchanging data: web APIs, configuration files and many databases use it. It looks almost exactly like Python dictionaries and lists.

JSON
{
  "name": "Asha",
  "age": 21,
  "skills": ["Python", "SQL"],
  "member": true,
  "manager": null
}

Python to JSON: dumps

json.dumps() ("dump string") turns Python data into JSON text:

Python
import json

profile = {"name": "Asha", "age": 21, "skills": ["Python", "SQL"], "member": True, "manager": None}
text = json.dumps(profile)
print(text)
print(type(text))
print(json.dumps(profile, indent=2))     # pretty-printed

Notice the translations: True → true, None → null, and single quotes become double quotes.

JSON to Python: loads

json.loads() ("load string") parses JSON text into Python objects:

Python
import json

response = '{"city": "Osaka", "temperature": 21.5, "forecast": ["sun", "cloud", "rain"]}'
weather = json.loads(response)
print(weather["city"], weather["temperature"])
print(weather["forecast"][2])
print(type(weather))

Type mapping

JSONPython
object {}dict
array []list
stringstr
numberint or float
true / falseTrue / False
nullNone

Files: dump and load

Without the "s", the functions work with files:

Python
import json

settings = {"theme": "dark", "font_size": 15, "autosave": True}
with open("settings.json", "w") as f:
    json.dump(settings, f, indent=2)

with open("settings.json") as f:
    loaded = json.load(f)
print(loaded)
print(loaded == settings)

Invalid JSON

Python
import json

bad = "{'name': 'Asha'}"        # single quotes aren't valid JSON
try:
    json.loads(bad)
except json.JSONDecodeError as e:
    print("Invalid JSON:", e)

JSON is stricter than Python: keys must be strings in double quotes, and trailing commas aren't allowed.

Working with nested API data

Python
import json

data = json.loads("""
{"orders": [
  {"id": 101, "items": [{"product": "Keyboard", "price": 89.99}, {"product": "Mouse", "price": 24.5}]},
  {"id": 102, "items": [{"product": "Monitor", "price": 279.0}]}
]}
""")
for order in data["orders"]:
    total = sum(item["price"] for item in order["items"])
    print(f"Order {order['id']}: {total:.2f}")
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.