Python — JSON
JSON ↔ Python dictionary
JSON is the internet's data format; Python speaks it natively via the json module:
import json
data = '{"name": "Ada", "age": 36, "langs": ["py", "js"]}'
user = json.loads(data) # parse string → dict
user["name"] # "Ada"
user["langs"][0] # "py"
| Python | JSON |
|---|---|
| dict | object |
| list | array |
| str | string |
| int / float | number |
| True / False | true / false |
| None | null |
dumps — the reverse direction
user = {"name": "Ada", "admin": False}
json.dumps(user)
# '{"name": "Ada", "admin": false}'
# pretty-printed for humans:
print(json.dumps(user, indent=2))
# {
# "name": "Ada",
# "admin": false
# }
Handy flags: indent=2 · sort_keys=True · separators=(",", ":") for compact.
Files: load & dump (no s!)
# write
with open("config.json", "w") as f:
json.dump(settings, f, indent=2)
# read
with open("config.json") as f:
settings = json.load(f)
Memory aid: the s versions work with strings; without s — files.
Talking to APIs (the real-world use)
import urllib.request # or requests after pip install
with urllib.request.urlopen("https://api.github.com/users/octocat") as r:
user = json.loads(r.read())
user["name"], user["public_repos"]
Handling bad JSON gracefully
try:
data = json.loads(user_input)
except json.JSONDecodeError as e:
print(f"Invalid JSON at line {e.lineno}: {e.msg}")
data = {}
Non-string keys gotcha
JSON keys are ALWAYS strings:
json.dumps({1: "a"}) # '{"1": "a"}' — int key became text!
json.loads('{"1": "a"}') # {"1": "a"} — still a STRING key
Round-tripping dicts with non-string keys silently mutates them.
Custom objects need help
class User:
def __init__(self, name): self.name = name
json.dumps(User("Ada"))
# TypeError: Object of type User is not JSON serializable
json.dumps(User("Ada"), default=lambda o: o.__dict__) # ✓
User(**json.loads('{"name":"Ada"}')) # back to object
Mini Practice
- Round-trip a nested dict through dumps/loads.
- Pretty-print with indent=2 + sorted keys.
- Save/load a settings dict to a real file.
- Fetch any public API; extract three fields.
- Catch JSONDecodeError from deliberately broken input.
Next: RegEx →
Related Topics
Frequently Asked Questions about JSON
What is JSON in Python?
JSON is a fundamental concept in Python. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn JSON?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn JSON.
Why is JSON important in Python?
JSON is essential for Python development. Understanding this concept will help you write better code and solve real-world problems more effectively.