JSON (JavaScript Object Notation) is the text format that web APIs, configuration files and many databases use to exchange data. It looks almost exactly like Python dictionaries and lists, and Python’s built-in json module converts between the two in one call. The File Handling lesson showed saving and loading a list; this lesson goes further, covering conversion rules, pretty printing, API-style data, custom types and error handling.
In this lesson you will learn
json.dumpsandjson.loadsfor stringsjson.dumpandjson.loadfor files- How Python and JSON types map to each other
- Pretty printing with
indentandsort_keys - Handling dates and other unsupported types, and invalid JSON
Converting Between Python and JSON
import json
student = {
"name": "Nusrat",
"cgpa": 3.82,
"graduated": False,
"courses": ["Data Structures", "Databases"],
"advisor": None,
}
text = json.dumps(student) # Python object -> JSON string
print(text)
print(type(text).__name__)
pretty = json.dumps(student, indent=2, sort_keys=True)
print(pretty)
back = json.loads(text) # JSON string -> Python object
print(back["courses"][1], back["graduated"], back["advisor"])
print(back == student)
Output
{"name": "Nusrat", "cgpa": 3.82, "graduated": false, "courses": ["Data Structures", "Databases"], "advisor": null}
str
{
"advisor": null,
"cgpa": 3.82,
"courses": [
"Data Structures",
"Databases"
],
"graduated": false,
"name": "Nusrat"
}
Databases False None
True
json.dumps()(“dump string”) turns a Python object into a JSON string. Notice the changes:Falsebecomesfalse,Nonebecomesnull, and all strings use double quotes.indent=2spreads the output over several lines for people to read;sort_keys=Truesorts the keys alphabetically.json.loads()(“load string”) parses JSON text back into Python dictionaries and lists, and the round trip gives an equal object.
| Python | JSON |
|---|---|
dict | object {} |
list, tuple | array [] |
str | string (double quotes) |
int, float | number |
True / False | true / false |
None | null |
API Data, Files, Custom Types and Errors
import json
from datetime import date
# A response like one from a web API
response = '''
{"status": "ok",
"results": [
{"id": 1, "city": "Dhaka", "temp": 31.5},
{"id": 2, "city": "Sylhet", "temp": 27.0},
{"id": 3, "city": "Khulna", "temp": 33.2}
]}
'''
data = json.loads(response)
hot = [r["city"] for r in data["results"] if r["temp"] > 30]
print("Hot cities:", hot)
print("Missing key with .get():", data.get("page", 1))
# Tuples become lists; keys are always strings
print(json.loads(json.dumps({1: (2, 3)})))
# Types JSON does not know need help
event = {"title": "Exam", "on": date(2026, 12, 20)}
try:
json.dumps(event)
except TypeError as e:
print("TypeError:", e)
print(json.dumps(event, default=str))
with open("settings.json", "w", encoding="utf-8") as f:
json.dump({"theme": "dark", "lang": "bn"}, f, ensure_ascii=False)
with open("settings.json", encoding="utf-8") as f:
print(json.load(f))
try:
json.loads("{'name': 'x'}") # single quotes are not valid JSON
except json.JSONDecodeError as e:
print("JSONDecodeError:", e.msg)
import os; os.remove("settings.json")
Output
Hot cities: ['Dhaka', 'Khulna']
Missing key with .get(): 1
{'1': [2, 3]}
TypeError: Object of type date is not JSON serializable
{"title": "Exam", "on": "2026-12-20"}
{'theme': 'dark', 'lang': 'bn'}
JSONDecodeError: Expecting property name enclosed in double quotes
- API responses are usually a dictionary containing lists of dictionaries. After
json.loads, ordinary indexing and comprehensions pull out what you need. Use.get()for keys that may be missing. - The conversion is not perfectly reversible: tuples come back as lists, and dictionary keys always come back as strings (
1became'1'). - Objects JSON has no type for, such as
date,datetime, sets or your own classes, raiseTypeError. Thedefaultargument supplies a converter;default=stris a quick fix, and a custom function gives full control. json.dump(obj, file)andjson.load(file)work directly with open files.ensure_ascii=Falsekeeps non-English text, such as Bangla, readable in the file instead of escaping it as\ucodes.- Invalid JSON raises
json.JSONDecodeError. Single quotes, trailing commas and comments are all invalid in JSON, even though they are fine in Python.
Common Mistakes
- Confusing
dumpanddumps: the version ending in s works with strings, the other with files. - Building JSON by string concatenation, which breaks on quotes and special characters; always use
json.dumps. - Expecting integer keys to survive a round trip.
- Calling
str(dict)and treating the result as JSON; it uses single quotes andTrue/None, which JSON rejects.
Practice Exercises
Exercise 1. Parse '{"items": [{"name": "pen", "price": 20}, {"name": "bag", "price": 950}]}' and print the total price.
Show answer
import json
data = json.loads('{"items": [{"name": "pen", "price": 20}, {"name": "bag", "price": 950}]}')
print(sum(item["price"] for item in data["items"])) # 970
Exercise 2. Write a default function that converts sets to sorted lists, so json.dumps({"tags": {"b", "a"}}, default=...) works.
Show answer
def encode(obj):
if isinstance(obj, set):
return sorted(obj)
raise TypeError(f"Cannot encode {type(obj).__name__}")
print(json.dumps({"tags": {"b", "a"}}, default=encode)) # {"tags": ["a", "b"]}
Frequently Asked Questions
How do I get JSON from a web API?
Fetch the response with a library such as requests and call response.json(), which runs json.loads on the body for you. With only the standard library, use urllib.request and then json.loads.
What is the difference between JSON and a Python dictionary?
A dictionary is a Python object in memory. JSON is text that follows strict rules so any language can read it. The json module translates between the two.
Summary
dumps/loadsconvert to and from strings;dump/loaduse files.- JSON uses double quotes,
true,falseandnull. - Use
indentfor readable output andensure_ascii=Falsefor non-English text. - Handle unsupported types with
defaultand bad input withJSONDecodeError.
Next: Python collections Module.
