Horje
Convert Bytes To Json using Python

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.

Python3

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)

Output

{'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.

Python3

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)

Output

{'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.

Python3

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)

Output

{'name': 'John', 'age': 30, 'city': 'New York', 'skills': ['Python', 'JavaScript']}






Reffered: https://www.geeksforgeeks.org


Python

Related
Sort Tuple of Lists in Python Sort Tuple of Lists in Python
Cannot Convert String To Float in Python Cannot Convert String To Float in Python
Subtract Two Numbers in Python Subtract Two Numbers in Python
How To Upgrade Plotly To Latest Version? How To Upgrade Plotly To Latest Version?
Convert Dictionary of Dictionaries to Python List of Dictionaries Convert Dictionary of Dictionaries to Python List of Dictionaries

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
12