The Wayback Machine - https://web.archive.org/web/20240921063315/https://www.geeksforgeeks.org/convert-a-bytes-array-into-json-format-in-python/
Open In App

Convert a Bytes Array into Json Format in Python

Last Updated : 06 Feb, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In Python, dealing with bytes data is common, and converting a bytes array to JSON format is a frequent task. In this article, we will see how to convert a bytes array into JSON format in Python.

Python Convert a Bytes Array into JSON Format

Below are some of the ways by which we can convert a bytes array into JSON format in Python:

  • Using decode and json.loads()
  • Using str() with decode and json.loads()
  • Using bytes.decode and io Module
  • Using json.JSONDecoder with Custom Decoder

Convert A Bytes Array Into Json Format Using decode and json.loads

In this example, we decode the bytes array into a string using ‘utf-8’ encoding and then parse it as JSON using the json.loads method.

Python3
import json

byte = b'[{\'Date\': \'2016-05-21T21:35:40Z\', \'CreationDate\': \'2012-05-05\',\
    \'LogoType\': \'png\', \'Ref\': 164611595, \'Classe\': [\'Email addresses\', \
    \'Passwords\'],\'Link\':\'http://some_link.com\'}]'

byte = byte.decode().replace("'", '"')
ans = json.loads(byte)
print(ans)

Output:

<class 'bytes'>
[{'Date': '2016-05-21T21:35:40Z',
'CreationDate': '2012-05-05',
'LogoType': 'png',
'Ref': 164611595,
'Classe': ['Email addresses', 'Passwords'],
'Link': 'http://some_link.com'}]
<class 'list'>

Bytes Array into JSON Format Using str() with decode and json.loads

In this example, we utilize the str constructor to convert the bytes array into a string and then parse it as JSON using json.loads.

Python3
import json

# Sample complex bytes array
bytes_data = b'{&quot;key&quot;: &quot;value&quot;, &quot;nested&quot;: {&quot;inner_key&quot;: [1, 2, 3]}}'
print(type(bytes_data))

# Convert bytes to string and parse as JSON
json_data = json.loads(str(bytes_data, 'utf-8'))

# Display the resulting JSON data
print(json_data)
print(type(json_data))

Output
<class 'bytes'>
{'key': 'value', 'nested': {'inner_key': [1, 2, 3]}}
<class 'dict'>

Bytes Array into JSON Format Using decode and io Module

In this example, we are using decode(), json.loads() and io module to convert a bytes array into JSON format in Python.

Python3
import json
import io

byte = b'[{\'Date\': \'2016-05-21T21:35:40Z\', \'CreationDate\': \'2012-05-05\', \
    \'LogoType\': \'png\', \'Ref\': 164611595, \'Classe\': [\'Email addresses\',\
    \'Passwords\'],\'Link\':\'http://some_link.com\'}]'
print(type(byte))
fix_bytes = byte.replace(b&quot;'&quot;, b'&quot;')

my_json = json.load(io.BytesIO(fix_bytes))  
print(my_json)
print(type(my_json))

Output:

<class 'bytes'>
[{'Date': '2016-05-21T21:35:40Z',
'CreationDate': '2012-05-05',
'LogoType': 'png',
'Ref': 164611595,
'Classe': ['Email addresses', 'Passwords'],
'Link': 'http://some_link.com'}]
<class 'list'>

Convert Bytes Array into JSON Format Using json.JSONDecoder Class

In this example, we create a custom JSON decoder using the json.JSONDecoder class, allowing us to handle complex scenarios or specific decoding requirements.

Python3
import json

# Sample complex bytes array
bytes_data = b'{&quot;key&quot;: &quot;value&quot;, &quot;nested&quot;: {&quot;inner_key&quot;: [1, 2, 3]}}'

# Custom JSON decoder for more complex scenarios
class ComplexDecoder(json.JSONDecoder):
    def decode(self, s, **kwargs):
        # Implement custom decoding logic if needed
        return super().decode(s, **kwargs)

print(type(bytes_data))
# Decode bytes using the custom decoder
json_data = json.loads(bytes_data, cls=ComplexDecoder)

# Display the resulting JSON data
print(json_data)
print(type(json_data))

Output
<class 'bytes'>
{'key': 'value', 'nested': {'inner_key': [1, 2, 3]}}
<class 'dict'>


Similar Reads

Find length of one array element in bytes and total bytes consumed by the elements in Numpy
In NumPy we can find the length of one array element in a byte with the help of itemsize . It will return the length of the array in integer. And in the numpy for calculating total bytes consumed by the elements with the help of nbytes. Syntax: array.itemsize Return :It will return length(int) of the array in bytes. Syntax: array.nbytes Return :It
1 min read
How to Convert Bytes to Int in Python?
A bytes object can be converted to an integer value easily using Python. Python provides us various in-built methods like from_bytes() as well as classes to carry out this interconversion. int.from_bytes() method A byte value can be interchanged to an int value by using the int.from_bytes() method. This method requires at least Python 3.2 and has t
2 min read
How to Convert Bytes to String in Python ?
In this article, we are going to cover various methods that can convert bytes to strings using Python. Convert bytes to a string Different ways to convert Bytes to string in Python: Using decode() methodUsing str() functionUsing codecs.decode() methodUsing map() without using the b prefixUsing pandas to convert bytes to strings Data types are the c
3 min read
Convert Bytes To Bits in Python
Among the must-have computer science and programming skills, having bit-level knowledge is one of those important things that you should know what it means to understand the data change in this big world. However, a potential need often arises for the conversion of bytes and bits in digital information into alternative units. In this article, we wi
2 min read
Convert Bytearray To Bytes In Python
In Python, dealing with binary data is a common task, and understanding how to convert between different binary representations is crucial. One such conversion is from a bytearray to bytes. In this article, we will explore five simple methods to achieve this conversion, along with code examples for each. Convert Bytearray To Bytes In PythonBelow, a
3 min read
Convert Unicode to Bytes in Python
Unicode, often known as the Universal Character Set, is a standard for text encoding. The primary objective of Unicode is to create a universal character set that can represent text in any language or writing system. Text characters from various writing systems are given distinctive representations by it. Convert Unicode to Byte in PythonBelow, are
2 min read
Convert Hex String to Bytes in Python
Hexadecimal strings are a common representation of binary data, especially in the realm of low-level programming and data manipulation. In Python, converting a hex string to bytes is a frequent task, and there are various methods to achieve this. In this article, we will explore some simple and commonly used methods for converting a hex string to b
3 min read
Convert from '_Io.Bytesio' to a Bytes-Like Object in Python
In Python, converting from _io.BytesIO to a bytes-like object involves handling binary data stored in a BytesIO object. This transformation is commonly needed when working with I/O operations, allowing seamless access to the raw byte representation contained within the BytesIO buffer. Various methods can be used to Convert From '_Io.Bytesio' To A B
2 min read
How to Convert Int to Bytes in Python?
An int object can be used to represent the same value in the format of the byte. The integer represents a byte, is stored as an array with its most significant digit (MSB) stored at either the start or end of the array. Method 1: int.tobytes() An int value can be converted into bytes by using the method int.to_bytes(). The method is invoked on an i
4 min read
Convert JSON data Into a Custom Python Object
Let us see how to convert JSON data into a custom object in Python. Converting JSON data into a custom python object is also known as decoding or deserializing JSON data. To decode JSON data we can make use of the json.loads(), json.load() method and the object_hook parameter. The object_hook parameter is used so that, when we execute json.loads(),
2 min read
How to convert pandas DataFrame into JSON in Python?
Data Analysis is an extremely important tool in today's world. A key aspect of Data Analytics is an organized representation of data. There are numerous data structures in computer science to achieve this task. In this article, we talk about two such data structures viz. Pandas DataFrame and JSON. Further, we see how to convert DataFrames to JSON f
4 min read
Convert an image into jpg format using Pillow in Python
Let us see how to convert an image into jpg format in Python. The size of png is larger when compared to jpg format. We also know that some applications might ask for images of smaller sizes. Hence conversion from png(larger ) to jpg(smaller) is needed. For this task we will be using the Image.convert() method of the Pillow module. Algorithm : Impo
2 min read
How to Convert Models Data into JSON in Django ?
Django is a high-level Python based Web Framework that allows rapid development and clean, pragmatic design. It is also called batteries included framework because Django provides built-in features for everything including Django Admin Interface, default database SQLlite3, etc. How to Convert Models Data Into Json Data In Django ? First create new
2 min read
Python - Difference between json.dump() and json.dumps()
JSON is a lightweight data format for data interchange which can be easily read and written by humans, easily parsed and generated by machines. It is a complete language-independent text format. To work with JSON data, Python has a built-in package called json. Note: For more information, refer to Working With JSON Data in Python json.dumps() json.
2 min read
Python - Difference Between json.load() and json.loads()
JSON (JavaScript Object Notation) is a script (executable) file which is made of text in a programming language, is used to store and transfer the data. It is a language-independent format and is very easy to understand since it is self-describing in nature. Python has a built-in package called json. In this article, we are going to see Json.load a
3 min read
json.loads() vs json.loads() in Python
orjson.loads() and json.loads() are both Python methods used to deserialize (convert from a string representation to a Python object) JSON data. orjson and json are both Python libraries that provide functions for encoding and decoding JSON data. However, they have some differences in terms of performance and compatibility. json is a built-in Pytho
4 min read
NumPy ndarray.byteswap() Method | Swap bytes of the Array Elements
The ndarray.byteswap() method swaps the bytes of the array elements. It toggles between low-endian and big-endian data representation by returning a byteswapped array, optionally swapped in-place. Note: byteswap() method does not work on arrays of strings. Example C/C++ Code # Python program explaining # byteswap() function import numpy as geek # a
2 min read
Python - Write Bytes to File
Files are used in order to store data permanently. File handling is performing various operations (read, write, delete, update, etc.) on these files. In Python, file handling process takes place in the following steps: Open filePerform operationClose file There are four basic modes in which a file can be opened― read, write, append, and exclusive c
2 min read
Python bytes() method
Python byte() function converts an object to an immutable byte-represented object of a given size and data. Example: Input: 2 Output: b'\x00\x00' Input: Python Output: b'Python'Python bytes() Method Syntax The bytes() method in Python has the following syntax. Syntax : bytes(src, enc, err) Parameters: src : The source object which has to be convert
4 min read
Retaining the padded bytes of Structural Padding in Python
Structural Padding means aligning the data into blocks of fixed size in order to ease the operations of particular Computer Architectures, Cryptographic algorithms accordingly. We pad(add enough bytes) the operational data (which is not necessarily structured) in order to serve the machine. Padded bytes may interrupt the original data, to identify
2 min read
How to Format JSON in VSCode
VSCode offers multiple ways to format JSON files, making it easy for developers to choose the method that best suits their workflow. A well-formatted JSON file is easier to read, understand, and debug, especially when working with complex data structures. Formatting JSON in VSCodeLet us see these ways one by one. JSON formatting refers to the way J
2 min read
How to Parse Data From JSON into Python?
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write for machines to parse and generate. Basically it is used to represent data in a specified format to access and work with data easily. Here we will learn, how to create and parse data from JSON and work with it. Before starting the det
2 min read
Python Encode Unicode and non-ASCII characters into JSON
This article will provide a comprehensive guide on how to work with Unicode and non-ASCII characters in Python when generating and parsing JSON data. We will look at the different ways to handle Unicode and non-ASCII characters in JSON. By the end of this article, you should have a good understanding of how to work with Unicode and non-ASCII charac
5 min read
Convert Array of Datetimes into Array of Strings in Python
In this article, we will convert an array of Datetimes into an array of strings. we have an array whose data type is DateTime and we want to change it to string. The shape and size of the array will be the same as the input array but the data type will be different. We will begin with an introduction and then progress through the methods for conver
4 min read
Save API data into CSV format using Python
In this article, we are going to see how can we fetch data from API and make a CSV file of it, and then we can perform various stuff on it like applying machine learning model data analysis, etc. Sometimes we want to fetch data from our Database Api and train our machine learning model and it was very real-time by applying this method we can train
6 min read
Convert JSON to CSV in Python
The full form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-
3 min read
Convert Text file to JSON in Python
JSON (JavaScript Object Notation) is a data-interchange format that is human-readable text and is used to transmit data, especially between web applications and servers. The JSON files will be like nested dictionaries in Python. To convert a text file into JSON, there is a json module in Python. This module comes in-built with Python standard modul
4 min read
Convert multiple JSON files to CSV Python
In this article, we will learn how to convert multiple JSON files to CSV file in Python. Before that just recall some terms : JSON File: A JSON file may be a file that stores simple data structures and objects in JavaScript Object Notation (JSON) format, which may be a standard data interchange format. It is primarily used for transmitting data bet
8 min read
Convert class object to JSON in Python
Conversion of the class object to JSON is done using json package in Python. json.dumps() converts Python object into a json string. Every Python object has an attribute which is denoted by __dict__ and this stores the object's attributes. Object is first converted into dictionary format using __dict__ attribute.This newly created dictionary is pas
2 min read
Convert HTML source code to JSON Object using Python
In this post, we will see how we can convert an HTML source code into a JSON object. JSON objects can be easily transferred, and they are supported by most of the modern programming languages. We can read JSON from Javascript and parse it as a Javascript object easily. Javascript can be used to make HTML for your web pages. We will use xmltojson mo
3 min read