Object of type is not JSON serializable in Python

Are you looking for a simple way to fix Object of type ARandomClass is not JSON serializable where ARandomClass is a built-in Python object or a custom class you’ve defined on your own. You’re probably trying to encode a Python object to a JSON formatted string. In this article, we will show you a few cases where this error would happen, and how to avoid it in the future.

Object of type is not JSON serializable

“Object of type is not JSON serializable” is a common error message in Python. It basically says that the built-in json module cannot transform the current object type into a JSON-formatted string.

The built-in json module of Python can only handle basic Python objects such as dictionaries, lists, strings, numbers, None, etc. Below is a table of how native Python objects are translated to JSON.

PythonJSON
dictobject
listtuplearray
strstring
intlongfloatnumber
Truetrue
Falsefalse
Nonenull

Now you have two options to handle Object of type is not JSON serializable

  • Create a custom JSON decoder for the object type of your choice. (https://pynative.com/make-python-class-json-serializable/)
  • Fix your script so that it returns one of the Python primitives mentioned above.

Decode bytes to string before serialization

If you’re seeing something like “Object of type bytes is not JSON serializable”, it means that json module has failed to convert a bytes object into JSON formatted string. What you have to do is either removing string.encode() calls or adding string.decode() to make sure that json.dumps() only takes in raw string as input. Consider the code below:

import json bytes_object = 'mystring'.encode('utf-8') json_str = json.dumps({'message': bytes_object})
Code language: Python (python)

In the code snippet, we’ve tried passing a bytes object into json.dumps, which will eventually result in “TypeError: Object of type ‘bytes’ is not JSON serializable”. In order to get rid of it, we can either remove the string.encode() call or add a string.decode() call before actually serialize the object.

Writing a custom JSON encoder

The json module relies on its “encoders” to transform native Python objects to strings. By default, every single object is passed onto an instance of json.JSONEncoder class which must have encode(), default() and iterencode() methods to do the serialization.

In order to serialize your own object type, you would have to overload json.JSONEncoder and implement custom encode(), default() and iterencode() methods. Let’s look at an example where we define a new class and encode it to JSON:

import json from json import JSONEncoder class CustomData: def __init__(self, name, value): self.name = name self.value = value class CustomEncoder(json.JSONEncoder): def default(self, o): return o.__dict__ # Create an instance and serialize it with our new encoder the_value = CustomData("Paris", 120) jsonized = json.dumps(the_value, indent=4, cls=CustomEncoder) print(jsonized)

We’ll see something like this :

{ "name": "Paris", "value": 120, }
Code language: JSON / JSON with Comments (json)

Use jsonpickle

If you need a quick and dirty solution without involving in too much coding, then jsonpickle is made for you.

jsonpickle is a Python library for serialization and deserialization of complex Python objects to and from JSON.

jsonpickle is built so that it allows more complex data structure to be serialized right out of the box. Most of the time, jsonpickle can take almost any Python object and turn the object into JSON. Additionally, it can reconstitute the object back into Python.

Under the hood, jsonpickle uses the same toolset you’re already familiar with : stdlib’s json, simplejson, and demjson. By default, it uses built-in json library from stdlib, but you can choose another JSON backend as well as roll your own backend if you want.

Below is an example of how we would serialize an object with jsonpickle:

import jsonpickle class Thing(object): def __init__(self, name): self.name = name obj = Thing('Awesome') frozen = jsonpickle.encode(obj)

We hope that the information above helped you fix “Object of type is not JSON serializable” error message in Python. We’ve written a few other guides on troubleshooting other common Python problems such as Fix Python Unresolved Import in VSCode, Fix “Max retries exceeded with URL” error in Python requests library and Fix locale.Error: unsupported locale setting in Python.

If you have any suggestion, please feel free to leave a comment below.

Click to rate this post!
[Total: 0 Average: 0]

Leave a Comment