Python JSON
The json module converts between Python objects and JSON strings. Standard library — no install needed.
Dump & load
PYTHON
import json
user = {'name': 'Ada', 'roles': ['admin', 'dev'], 'active': True}
text = json.dumps(user) # Python → JSON string
print(text)
back = json.loads(text) # JSON string → Python
print(back['roles'])
Pretty-print
PYTHON
print(json.dumps(user, indent=2, sort_keys=True))
Files
PYTHON
with open('user.json', 'w') as f:
json.dump(user, f, indent=2)
with open('user.json') as f:
back = json.load(f)
What converts
| Python | JSON |
|---|---|
dict | object |
list, tuple | array |
str | string |
int, float | number |
True, False | true, false |
None | null |
Non-JSON types
By default datetime, Decimal, sets, and your own classes aren't JSON-serialisable. Tell json.dumps how:
PYTHON
from datetime import datetime
def encode(obj):
if isinstance(obj, datetime):
return obj.isoformat()
raise TypeError
print(json.dumps({'when': datetime.now()}, default=encode))
Tip: For typed parsing into dataclasses or models, libraries like
pydantic and msgspec are faster and safer than hand-rolled json.loads + dict shuffling.Example
Example
import json
user = {'name': 'Ada', 'roles': ['admin', 'dev']}
text = json.dumps(user, indent=2)
print(text)
back = json.loads(text)
print(back['roles'])
Try it Yourself »
Exercise
Convert a Python dict to a JSON string.
text = json.
(user)
Five letters; plural verb.
Discussion
Loading…