Back to main.

Calmcode Shorts

In Python you have a json module that can turn Python dictionaries into valid JSON strings.

import json

json.dumps({'hello': "there"})

Even when we mix single ' and double " quotation symbols, the json.dumps call will make sure that we get valid json out.

Numpy and Datetime

Unfortunately, the json library that comes with Python isn't always able to turn objects into a valid JSON representation. Common culprits include datetime objects and numpy arrays.

import numpy as np
import datetime as dt

# ...
# TypeError: Object of type datetime is not JSON serializable

json.dumps({"array": np.random.normal(0, 1, 5)})
# ...
# TypeError: Object of type ndarray is not JSON serializable

This is where orjson can help us!

Enter orjson

Let's now construct a dictionary with many different types.

data = {
    'hello': 'world',
    'number': 5.1,
    "int": 10,
    "array": np.random.normal(0, 1, 5),
    "inf": float("-inf")

To serialize this into JSON, we can use the orjson.dumps call, which closely mimics the expected behavior from json.dumps.

# For Numpy arrays we need to add an extra flag.
orjson.dumps(data, option=orjson.OPT_SERIALIZE_NUMPY).decode()

This is what the resulting JSON string contains:


The datetime object is turned into a string, the Numpy array becomes a list of numbers and the infinity value becomes a null.

More Details

Depending on the types that you want to serialize you may need to add some custom translators or extra options. More information on that can be found on the project homepage.

Back to main.