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

PythonJSONProgramming

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}"
raja
Published on 18-Apr-2018 12:31:32
Advertisements