TypeError: Object of type bytes is not JSON serializable

Are you getting the error “typeerror: object of type bytes is not json serializable“? Yes, you have come to the right place. Today, I will show you how to solve this error.

The error “object of type ‘bytes’ is not json serializable” occurs when we try to convert the bytes object to a JSON string.

[Fixed] typeerror: object of type bytes is not json serializable

If you get the error “typeerror: object of type bytes is not json serializable” it means your string is encoded in bytes. To solve this error, we need to call the decode() function on the bytes object to decode the bytes to a string before serializing them to JSON.

[Fixed]: ModuleNotFoundError: No module named ‘tkinter’ in Python

Here is an example of how this typeerror: object of type bytes is not json serializableoccurs:

import json
my_bytes = 'Ehtisham Ali Qazipur'.encode('utf-8')
# TypeError: Object of type bytes is not JSON serializable
json_str = json.dumps({'message': my_bytes})

In the above code, we are trying to pass the bytes object to the ‘json.dumps‘ but by default, it does not accept the bytes object.

To solve this error, you can remove the ‘.encode()‘ or use the ‘.decode()‘ method. “.decode()” will against convert bytes object to the sting.

import json

my_bytes = 'ALI AWAN QAZIPUR'.encode('utf-8')

# decode bytes object
my_bytes = my_bytes.decode('utf-8')

json_str = json.dumps({'message': my_bytes })

print(json_str)  #OUTPUT : '{"message": "ALI AWAN QAZIPUR"}'
print(type(json_str))  #OUTPUT : <class 'str'>

[Solution] typeerror: object of type bytes is not json serializable

An alternative way to solve the error is to use the ‘BytesEncoder‘ class. You can handle the conversions in a default method.

import json

class BytesEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, bytes):
            return obj.decode('utf-8')
        return json.JSONEncoder.default(self, obj)

my_bytes = 'EHTISHAM QAZIPUR'.encode('utf-8')

# pass the cls keyword argument
json_str = json.dumps({'message': my_bytes}, cls=BytesEncoder)

print(json_str)  #OUTPUT : '{"message": "EHTISHAM QAZIPUR"}'
print(type(json_str))  #OUTPUT : <class 'str'>

Conclusion: typeerror: object of type bytes is not json serializable

Programmers, We discussed how we can solve the error “typeerror: object of type bytes is not json serializable“. If you are still facing the issue, please let us know in the comments section. You can use the “decode()” method to solve this error.

Leave a Reply