When dealing with complex byte data in Python, converting it to JSON format is a common task. In this article, we will explore different approaches, each demonstrating how to handle complex byte input and showcasing the resulting JSON output.
Convert Bytes To JSON in Python
Below are some of the ways by which we can convert bytes to JSON in Python:
- Using json.loads() with decode()
- Using json.loads() with str()
- Using json.loads() with bytearray
Bytes To JSON in Python Using json.loads() with decode()
In this example, we use the json.loads() method and decode() method to convert bytes to JSON objects.
import json
# Complex byte data byte_data = b '{"name": "John", "age": 30, "city": "New York", "skills": ["Python", "JavaScript"]}'
json_data_1 = json.loads(byte_data.decode( 'utf-8' ))
print (json_data_1)
|
{'name': 'John', 'age': 30, 'city': 'New York', 'skills': ['Python', 'JavaScript']}
Python Bytes To JSON Using json.loads() with str()
Here, the json.loads() method is employed along with the str() function to convert bytes to a JSON object.
import json
# Complex byte data byte_data = b '{"name": "John", "age": 30, "city": "New York", "skills": ["Python", "JavaScript"]}'
json_data_2 = json.loads( str (byte_data, 'utf-8' ))
print (json_data_2)
|
{'name': 'John', 'age': 30, 'city': 'New York', 'skills': ['Python', 'JavaScript']}
Python Convert Bytes To Json Using json.loads() with bytearray
Here, we convert the byte data to a bytearray and then use the json.loads() method to obtain the JSON object.
import json
# Complex byte data byte_data = b '{"name": "John", "age": 30, "city": "New York", "skills": ["Python", "JavaScript"]}'
json_data_4 = json.loads(bytearray(byte_data))
print (json_data_4)
|
{'name': 'John', 'age': 30, 'city': 'New York', 'skills': ['Python', 'JavaScript']}