Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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}" Advertisements
