logo

JSON and Python Type Mapping

JSON has fewer types than Python. When converting, Python types map to their JSON equivalents:

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

This works both ways when parsing.

Some Python types don't have JSON equivalents:

import json
from datetime import datetime

data = {"timestamp": datetime.now()}
json.dumps(data)  # TypeError!

Dates, sets, and custom objects need special handling. You'll need to convert them to strings or basic types first.

data = {"timestamp": datetime.now().isoformat()}
json.dumps(data)  # Works - it's a string now

I explain type conversion in my JSON with Python course.