How can I convert a bytes array into JSON format in Python?


You need to decode the bytes object to produce a string. This can be done using the decode function from string class that will accept then encoding you want to decode with. 

example

my_str = b"Hello" # b means its a byte string
new_str = my_str.decode('utf-8') # Decode using the utf-8 encoding
print(new_str)

Output

This will give the output

Hello

Once you have the bytes as a string, you can use the JSON.dumps method to convert the string object to JSON. 

example

my_str = b'{"foo": 42}' # b means its a byte string
new_str = my_str.decode('utf-8') # Decode using the utf-8 encoding

import json
d = json.dumps(my_str)
print(d)

Output

This will give the output −

"{\"foo\": 42}"

Updated on: 05-Mar-2020

18K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements