Python json — Parse & Serialize JSON
JSON (JavaScript Object Notation) is the most common format for exchanging data between programs, APIs, and config files. Python’s built-in json module converts between JSON text and Python objects — no installation needed.
import json
data = {"name": "Ada", "age": 36, "skills": ["math", "code"]}
text = json.dumps(data) # Python -> JSON string
print(text) # {"name": "Ada", "age": 36, "skills": ["math", "code"]}
back = json.loads(text) # JSON string -> Python
print(back["skills"][0]) # mathThe four functions
Section titled “The four functions”The module has two pairs: one works with strings, the other with files.
| Function | Direction | Works with |
|---|---|---|
json.dumps(obj) | Python → JSON | A string (“dump string”). |
json.loads(text) | JSON → Python | A string (“load string”). |
json.dump(obj, file) | Python → JSON | A file object. |
json.load(file) | JSON → Python | A file object. |
Remember the s: dumps/loads end in s for string; dump/load are for files.
How types map
Section titled “How types map”Serialization converts Python types to their JSON equivalents (and back):
| Python | JSON |
|---|---|
dict | object |
list, tuple | array |
str | string |
int, float | number |
True / False | true / false |
None | null |
Note: tuples become JSON arrays, and JSON arrays always load back as lists — so a round-trip turns a tuple into a list.
Serializing: dumps
Section titled “Serializing: dumps”import json
data = {"name": "Ada", "active": True, "score": None, "tags": ["a", "b"]}
# Compact (default)
print(json.dumps(data))
# Pretty-printed with indentation
print(json.dumps(data, indent=2))
# Sort keys alphabetically
print(json.dumps(data, sort_keys=True))
# Custom separators for the most compact output
print(json.dumps(data, separators=(",", ":")))Common dumps / dump options:
| Option | Effect |
|---|---|
indent=n | Pretty-print with n spaces per level. |
sort_keys=True | Order object keys alphabetically. |
separators=(item, key) | Control the item and key-value separators. |
ensure_ascii=False | Keep non-ASCII characters as-is (e.g. emoji, accents). |
default=func | A fallback function to serialize unknown types. |
import json
data = {"city": "São Paulo", "emoji": "🐍"}
print(json.dumps(data)) # escapes non-ASCII
print(json.dumps(data, ensure_ascii=False)) # keeps São Paulo and 🐍 readableParsing: loads
Section titled “Parsing: loads”import json
text = '{"name": "Ada", "age": 36, "skills": ["math", "code"], "active": true}'
obj = json.loads(text)
print(type(obj)) # <class 'dict'>
print(obj["name"]) # Ada
print(obj["active"]) # True (JSON true -> Python True)
print(obj["skills"][1]) # codeWorking with files
Section titled “Working with files”Use dump/load to read and write JSON files directly.
import json
config = {"theme": "dark", "version": 2, "plugins": ["a", "b"]}
# Write to a file
with open("config.json", "w", encoding="utf-8") as f:
json.dump(config, f, indent=2)
# Read it back
with open("config.json", "r", encoding="utf-8") as f:
loaded = json.load(f)
print(loaded["theme"]) # darkHandling errors
Section titled “Handling errors”Invalid JSON raises json.JSONDecodeError (a subclass of ValueError). Always guard parsing of untrusted input.
import json
bad = '{"name": "Ada", }' # trailing comma is invalid JSON
try:
json.loads(bad)
except json.JSONDecodeError as e:
print("Could not parse:", e)Serializing custom objects
Section titled “Serializing custom objects”By default, json only knows the built-in types. For your own classes, pass a default function (or convert to a dict first).
import json
from datetime import datetime
def encode(obj):
if isinstance(obj, datetime):
return obj.isoformat()
raise TypeError(f"Cannot serialize {type(obj).__name__}")
event = {"name": "launch", "when": datetime(2025, 1, 31, 9, 0)}
print(json.dumps(event, default=encode))
# {"name": "launch", "when": "2025-01-31T09:00:00"}Practical example — a tiny API response
Section titled “Practical example — a tiny API response”import json
response = '''
{
"status": "ok",
"users": [
{"id": 1, "name": "Ada"},
{"id": 2, "name": "Linus"}
]
}
'''
data = json.loads(response)
for user in data["users"]:
print(user["id"], "->", user["name"])
# 1 -> Ada
# 2 -> LinusCommon pitfalls
Section titled “Common pitfalls”- Single quotes — JSON requires double quotes around keys and strings.
"{'a': 1}"fails; use'{"a": 1}'. - Trailing commas are invalid in JSON (unlike Python).
True/Nonevstrue/null— Python prints capitalized; JSON uses lowercase. The module handles the conversion for you, but watch for it when hand-writing JSON.- Non-serializable types (sets, datetimes, custom classes) raise
TypeErrorunless you supplydefault. - Keys become strings — JSON object keys are always strings, so
{1: "a"}serializes to{"1": "a"}.
Practice Exercises
Section titled “Practice Exercises”Exercise 1 – Serialize a dictionary
Section titled “Exercise 1 – Serialize a dictionary”Exercise 2 – Parse JSON and read a value
Section titled “Exercise 2 – Parse JSON and read a value”Exercise 3 – Pretty-print with indentation
Section titled “Exercise 3 – Pretty-print with indentation”Summary
Section titled “Summary”jsonconverts between JSON text and Python objects with four functions:dumps/loads(strings) anddump/load(files).- Python types map cleanly to JSON; tuples and JSON arrays both become lists on the way back.
- Format output with
indent,sort_keys,separators, andensure_ascii. - Guard parsing with
try/except json.JSONDecodeError. - Serialize custom types with a
defaultfunction.
pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading