Python: Convert Bytes inside a dict to json

Advertisements

I’m having the following dict:

{b'one': b'one', b'two': b'two', b'three': b'three'}

I want to convert this to a json object.

I already tried different things with json.dumps, but I only get errors.

How can I do this?

>Solution :

The issue you’re facing is due to the fact that the keys and values in your dictionary are bytes, not strings. The json.dumps() function in Python expects the keys and values to be of type str, int, float, bool, or None.

Use the following code to convert byte keys and values to strings;

dict_str = {k.decode('utf-8'): v.decode('utf-8') for k, v in dict_bytes.items()}

Leave a ReplyCancel reply