Custom JSON Encoder with python

Alexis Gomes
2 min readJun 17, 2020

The json package can encode python objects as strings with the json.JSONEncoder class, and decodes strings into python objects using the json.JSONDecoder class.

Here is an example :

import json

# Convert a dict to a string
json.dumps({"name": "Paul", "age": 24})

# Convert a string to a dict
json.loads('{"name": "Paul", "age": 24}')

By default, these class supports dict, list, tuple, str, int, float, bool and None values. But it’s possible to overload JsonEncoder and JsonDecoder to support Datetime, Decimal or any of your classes.

It can be useful when you want to serialize or deserialize objects. I like to use it when I store mongodb queries (which are json objects) as a string in database.

Let’s start with json encoding.

# extend the json.JSONEncoder class
class JSONEncoder(json.JSONEncoder):

# overload method default
def default(self, obj):

# Match all the types you want to handle in your converter
if isinstance(obj, datetime):
return arrow.get(obj).isoformat()
# Call the default method for other types
return json.JSONEncoder.default(self, obj)

In the above example, we convert datetime objects to isoformat string.

--

--