Custom JSON Encoder with python

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 :

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.

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

We can also convert Decimal or any other object

And let’s do the opposite with JSONDecoder. It’s a little bit different here, we have to pass a method to object_hook in the constructor. We will implement our custom deserializations conditions in this method.

We can add two shortcuts for a more readable code.

And use it this way

You can find all the code, with examples on Github : JsonEncoder.

If you want like to read more about the json package, you can refer to the documentation.

I work at yper. I’m a python developper, learning data-science. I’ve made a www.blindfoldchesstactic.com app. You can buy me coffee : www.buymeacoffee.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store