Open In App

How to Parse Json from Bytes in Python

Last Updated : 01 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

We are given a bytes object and we have to parse JSON object from it by using different approaches in Python. In this article, we will see how we can parse JSON with bytes in Python

Parse JSON With Bytes in Python

Below are some of the ways by which we can parse JSON with bytes in Python:

  1. Using the json.loads() function
  2. Decoding Bytes to Strings and Parsing JSON
  3. Handling Different Encodings
  4. Parsing JSON Data from an API Response

Using the json.loads() function

In this example, we start with JSON data represented as bytes (json_data). By decoding the bytes to a UTF-8 encoded string (decoded_data), we can then use json.loads to parse the JSON string into a Python dictionary (parsed_json). Finally, the parsed JSON is printed to the console.


Output
{'name': 'Amit', 'age': 30, 'city': 'Delhi'}

Decoding Bytes to Strings and Parsing JSON

In this example, we begin with JSON data represented as bytes (json_data). By decoding the bytes to a UTF-8 encoded string (decoded_data), we use json.loads to parse the JSON string into a Python dictionary (parsed_json). Subsequently, specific values such as name, age, and city are accessed from the parsed JSON, and these values are printed to the console.


Output
Name: Ankit
Age: 30
City: Mumbai

Handling Different Encodings

In this example, we have JSON data encoded as bytes using UTF-16 (json_data_utf16). By decoding the bytes with the appropriate encoding (utf-16 in this case) to obtain a string (decoded_data_utf16), we then use json.loads to parse the JSON string into a Python dictionary (parsed_json_utf16). Subsequently, specific values such as name, age, and city are accessed from the parsed JSON with UTF-16 encoding, and these values are printed to the console.


Output
Name (UTF-16): Anil
Age (UTF-16): 25
City (UTF-16): New York

Parsing JSON Data from an API Response

In this example, a request is made to an API endpoint using urllib.request.urlopen. The JSON data from the API response is obtained by reading the response (json_data_api). By decoding the bytes to a UTF-8 encoded string (decoded_data_api), json.loads is used to parse the JSON string into a Python dictionary (parsed_json_api). Subsequently, specific values such as user ID, title, and body are accessed from the parsed JSON, and these values are printed to the console.

Output:

User ID: 1
Title: sunt aut facere repellat provident occaecati excepturi optio reprehenderit
Body: quia et suscipit
suscipit recusandae consequuntur expedita et cum

Next Article
Practice Tags :

Similar Reads