iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

PythonJSON
dictobject
list, tuplearray
strstring
int, floatnumber
True, Falsetrue, false
Nonenull

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)

Test yourself

Q1. json.dumps converts…
Q2. datetime is JSON-serialisable by default?
Q3. For typed parsing into models, reach for…

Discussion

Loading…