- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
To Continue Learning Please Login
Login with Google