Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: Convert Bytes inside a dict to json

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading