Robert Brax
Robert Brax

Reputation: 7318

Convert a dict of bytes to json

I'm trying to convert:

response data = {'policy': b'eyJleHBpcmF0a', 'signature': b'TdXjfAp'}

to json:

jsonified = json.dumps( response_data )

but it results in error message:

TypeError: Object of type 'bytes' is not JSON serializable

What is the proper way to make the proper conversion ?

Expected result

jsonified = {"policy": "eyJleHBpcmF0a", "signature": "TdXjfAp"}

Upvotes: 0

Views: 10825

Answers (1)

Mike Scotty
Mike Scotty

Reputation: 10782

You could write your own encoder for types that can not be serialized out-of-the-box:

import json

class MyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, (bytes, bytearray)):
            return obj.decode("ASCII") # <- or any other encoding of your choice
        # Let the base class default method raise the TypeError
        return json.JSONEncoder.default(self, obj)

data = {'policy': b'eyJleHBpcmF0a', 'signature': b'TdXjfAp'}
jsonified = json.dumps( data, cls=MyEncoder )
print(jsonified)
# {"policy": "eyJleHBpcmF0a", "signature": "TdXjfAp"}

This approach can easily be extended to support other types, such das datetime.

Just make sure you end up with a str/int/float/... or any other serializeable type at the end of the function.

As @Tomalak pointed out, you could also use a base64 encoding instead of the ASCII encoding to make sure you support control characters.

Upvotes: 8

Related Questions