Python's built-in json module makes working with JSON straightforward. This guide covers every real-world scenario you'll encounter.
Parse JSON strings
import json
# json.loads() — string to Python object
json_string = '{"name": "Alice", "age": 28, "active": true}'
data = json.loads(json_string)
print(data['name']) # Alice
print(data['age']) # 28
print(type(data)) # <class 'dict'>
Create JSON strings
import json
data = {
'name': 'Alice',
'age': 28,
'tags': ['developer', 'python'],
'address': {'city': 'Paris'}
}
# Compact
json.dumps(data)
# Pretty-printed
json.dumps(data, indent=2)
# Sorted keys
json.dumps(data, indent=2, sort_keys=True)
# ASCII-safe (escape non-ASCII)
json.dumps({'emoji': '😀'}, ensure_ascii=True)
# '{"emoji": "\ud83d\ude00"}'
# Keep Unicode
json.dumps({'emoji': '😀'}, ensure_ascii=False)
# '{"emoji": "😀"}'
Read and write JSON files
import json
# Read JSON file
with open('data.json', 'r', encoding='utf-8') as f:
data = json.load(f)
# Write JSON file
with open('output.json', 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2, ensure_ascii=False)
Handle JSON from HTTP APIs
import requests # pip install requests
response = requests.get('https://api.example.com/users')
response.raise_for_status() # raises on 4xx/5xx
data = response.json() # parses JSON automatically
print(data[0]['name'])
Handle dates in JSON
from datetime import datetime, date
import json
# Dates aren't JSON-serializable by default
class DateEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, (datetime, date)):
return obj.isoformat()
return super().default(obj)
data = {'created': datetime.now(), 'date': date.today()}
json_str = json.dumps(data, cls=DateEncoder)
# '{"created": "2023-11-14T22:13:20.123456", "date": "2023-11-14"}'
Pretty-print JSON in terminal
# One-liner to format JSON from command line
echo '{"name":"Alice","age":28}' | python3 -m json.tool
# Format a file
python3 -m json.tool data.json
JSON type mapping
| JSON | Python |
|---|---|
object {} | dict |
array [] | list |
| string | str |
| number (int) | int |
| number (float) | float |
| true / false | True / False |
| null | None |
Try it free — JSON Formatter
Format and validate your JSON before working with it in Python.