Python JSON
Handle JSON in Python with dumps, loads, file read/write, and API data parsing.
What is JSON?
JSON (JavaScript Object Notation) is the most common format for exchanging data between systems —
especially web APIs. It looks similar to Python dictionaries and lists. Python's built-in
json module converts between Python objects and JSON strings. Key functions:
dumps = dict → string, loads = string → dict, dump = write to
file, load = read from file. The "s" suffix stands for "string".
Python → JSON with dumps()
Python True/False/None automatically become JSON true/false/null.
Use indent=2 for human-readable output.
import json data = {{"name": "Alice", "age": 28, "skills": ["Python", "SQL"], "active": True}} print(json.dumps(data)) # compact print(json.dumps(data, indent=2)) # pretty
{{"name": "Alice", "age": 28, "skills": ["Python", "SQL"], "active": true}}
{{
"name": "Alice",
"age": 28,
"skills": [
"Python",
"SQL"
],
"active": true
}}JSON → Python with loads()
loads() parses a JSON string into Python objects. This is what you use when you get
a response from a web API.
import json js = '{"city": "London", "temp": 12.5, "rain": true}' w = json.loads(js) print(type(w)) # dict print(w["city"]) print(w["rain"]) # JSON true → Python True
London True
Reading and Writing JSON Files
json.dump() writes to a file; json.load() reads from one. This is the
standard way to save configuration or persistent data between program runs.
import json cfg = {{"theme": "dark", "font": 14}} with open("config.json", "w") as f: json.dump(cfg, f, indent=2) with open("config.json") as f: loaded = json.load(f) print(loaded["theme"])
dark
default=str as a quick fallback.🧠 Quick Check
Which function converts a Python dict to a JSON string?