Working with JSON Data
JSON (JavaScript Object Notation) is the standard data format for APIs and config files. Python's json module makes it easy to read, write, and manipulate JSON data.
15 min•By Priygop Team•Updated 2026
JSON in Python
JSON in Python
import json
# Python dict → JSON string
data = {"name": "Alice", "age": 25, "skills": ["Python", "SQL"]}
json_str = json.dumps(data, indent=2)
print(json_str)
# JSON string → Python dict
json_text = '{"city": "Mumbai", "population": 20000000}'
parsed = json.loads(json_text)
print(parsed["city"])
print(type(parsed)) # <class 'dict'>
# Read JSON file
# with open("data.json", "r") as f:
# data = json.load(f)
# Write JSON file
# with open("output.json", "w") as f:
# json.dump(data, f, indent=2)
# Practical: API-like data
users = [
{"id": 1, "name": "Alice", "active": True},
{"id": 2, "name": "Bob", "active": False},
{"id": 3, "name": "Charlie", "active": True},
]
# Pretty print
print(json.dumps(users, indent=2))
# Filter active users
active = [u for u in users if u["active"]]
print(f"\nActive users: {len(active)}")
for user in active:
print(f" - {user['name']}")Tip
Tip
Use json.dumps(data, indent=2) for readable output. json.loads() parses strings, json.load() reads files.
Diagram
Loading diagram…
undefined/functions dropped. Always try/catch parse.
Common Mistake
Warning
JSON keys must be strings. Python dicts allow int keys: {1: 'a'}, but json.dumps({1: 'a'}) converts to {'1': 'a'}.
Practice Task
Note
(1) Convert a dict to JSON and back. (2) Pretty-print nested JSON. (3) Filter JSON data using comprehensions.