Python JSON
JavaScript Object Notation, more often known as JSON, is a data format that is extensively used for the purpose of data transfer on the internet. When it comes to structuring data in transit between a client and a server, JSON is the format of choice. Its syntax is somewhat similar to that of the computer language JavaScript. The primary purpose of the JSON format is to facilitate the transfer of data between the client and the web server. It is not only simple to understand but also the most efficient method for exchanging the data. It is compatible with a wide variety of computer languages, including Python, Perl, Java, and others. JSON primarily supports six different data types in JavaScript.
:
-
String
-
Number
-
Boolean
-
Null
-
Object
-
Array
JSON is constructed using both of them.
structures:
-
It stores data in the name/value pairs. It is treated as an
object, record, dictionary, hash table, keyed list
. - The ordered list of values is treated as an array, vector, list, or sequence.
The representation of data in JSON is comparable to that of the Python dictionary. An example of JSON may be seen below.
data:
-
{
-
“book”
: [
-
{
-
“id”
:
01
,
-
“language”
:
“English”
,
-
“edition”
:
“Second”
,
-
“author”
:
“Derrick Mwiti”
-
],
-
{
-
{
-
“id”
:
02
,
-
“language”
:
“French”
,
-
“edition”
:
“Third”
,
-
“author”
:
“Vladimir”
-
}
-
}
Working with Python JSON
There is a component in Python known as the json module. The JSON API works in a manner that is quite similar to that of the marshal and pickle modules that Python’s standard library provides. JSON features may be supported natively in Python.
The process of encoding data with JSON is referred to as Serialization. A method known as serialization is a process in which data is converted into a sequence of bytes before being sent across a network.
Deserialization is the process of decoding the data once it has been translated into JSON format. This process is the inverse of serialization.
This module comes with a plethora of pre-installed functionality.
Let’s have a gander at them, shall we?
functions:
-
import
json
-
print(dir(json))
Output:
['JSONDecodeError', 'JSONDecoder', 'JSONEncoder', '__all__', '__author__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__', '_default_decoder', '_default_encoder', 'codecs', 'decoder', 'detect_encoding', 'dump', 'dumps', 'encoder', 'load', 'loads', 'scanner']
These are the topics that will be covered in this section.
methods:
-
load()
-
loads()
-
dump()
-
dumps()
Serializing JSON
The process of converting Python objects to JSON uses a method called serialization. When the computer has to handle a large amount of data, it is a good idea to save that data in a file for later use. With the JSON function, we are able to save JSON data into a file. Python objects may be transformed via the use of the dump() and dumps() methods, which are both provided by the json module.
This is a conversion of Python objects into their corresponding JSON objects. The list is shown here.
below:
Sr. | Python Objects | JSON |
---|---|---|
1. |
Dict | Object |
2. |
list, tuple | Array |
3. |
Str | String |
4. |
int, float | Number |
5. |
True | true |
6. |
False | false |
7. |
None | null |
W01A3@@3 Sending Data in JSON Format to the File
Data may be sent (encoded) in JSON format using the dump() method, which is provided by Python. It takes two positional parameters, the first of which is the data object that is going to be serialized, and the second of which is the file-like object to which the bytes are going to be written.
Let’s start with the most basic kind of serialization.
example:
-
Import json
-
# Key:value mapping
-
student = {
-
“Name”
:
“Peter”
,
-
“Roll_no”
:
“0090014”
,
-
“Grade”
:
“A”
,
-
“Age”
:
20
,
-
“Subject”
: [
“Computer Graphics”
,
“Discrete Mathematics”
,
“Data Structure”
]
-
}
-
-
with open(
“data.json”
,
“w”
) as write_file:
-
json.dump(student,write_file)
Output:
{"Name" : "Peter", "Roll_no" : "0090014" , "Grade" : "A", "Age" : 20, "Subject" : ["Computer Graphics", "Discrete Mathematics", "Data Structure"] }
In the program that you just saw, we have opened a file with the name data.json and set it to writing mode. When we opened this file in write mode, a new copy of the file will be produced if it does not already exist. Dictionary data may be converted to JSON format using the json.dump() function.
string.
-
The dumps () function
Data that has been serialized may then be saved in the Python file with the help of the dumps() method. It is only possible to pass only one parameter, which should be Python data to be serialized. The file-like option is skipped over since we are not writing data to the disk at this time. Let’s have a look at the following, shall we?
example:
-
import
json
-
# Key:value mapping
-
student = {
-
“Name”
:
“Peter”
,
-
“Roll_no”
:
“0090014”
,
-
“Grade”
:
“A”
,
-
“Age”
:
20
-
}
-
b = json.dumps(student)
-
-
print(b)
Output:
{"Name": "Peter", "Roll_no": "0090014", "Grade": "A", "Age": 20}
Primitive data types, such as strings and integers, are supported by JSON, along with nested list, tuple, and array data types.
objects.
-
import
json
-
-
#Python list conversion to JSON Array
-
print(json.dumps([
‘Welcome’
,
“to”
,
“javaTpoint”
]))
-
-
#Python tuple conversion to JSON Array
-
print(json.dumps((
“Welcome”
,
“to”
,
“javaTpoint”
)))
-
-
# Python string conversion to JSON String
-
print(json.dumps(
“Hello”
))
-
-
# Python
int
conversion to JSON Number
-
print(json.dumps(
1234
))
-
-
# Python
float
conversion to JSON Number
-
print(json.dumps(
23.572
))
-
-
# Boolean conversion to their respective values
-
print(json.dumps(True))
-
print(json.dumps(False))
-
-
# None value to
null
-
print(json.dumps(None))
Output:
["Welcome", "to", "javaTpoint"] ["Welcome", "to", "javaTpoint"] "Hello" 1234 23.572 true false null
Deserializing JSON
Deserialization is the process of decoding JSON data into Python objects. It is also known as deserialization. The json module has two different methods, referred to as load() and loads(), that may be used to transform JSON data into real Python objects. The list is shown here.
below:
SR. | JSON | Python |
---|---|---|
1. |
Object | dict |
2. |
Array | list |
3. |
String | str |
4. |
number(int) | int |
5. |
true | True |
6. |
false | False |
7. |
null | None |
The table that can be seen above displays the reverse of the table that was serialized; however, strictly speaking, this is not an exact translation of the JSON data. That implies that if we encode the item and then decode it again after some time has passed, there is a possibility that we will not receive the identical thing back.
Take, for instance, the situation when one person translates something into Mandarin and another person translates back into English; the result may not be an accurate translation of the original. Think about the obvious.
example:
-
import
json
-
a = (
10
,
20
,
30
,
40
,
50
,
60
,
70
)
-
print(type(a))
-
b = json.dumps(a)
-
print(type(json.loads(b)))
Output:
<class 'tuple'> <class 'list'>
-
The load() function
The load() method is used in order to deserialize the JSON data included inside the file into a Python object. Take into consideration the following:
example:
-
import
json
-
# Key:value mapping
-
student = {
-
“Name”
:
“Peter”
,
-
“Roll_no”
:
“0090014”
,
-
“Grade”
:
“A”
,
-
“Age”
:
20
,
-
}
-
-
with open(
“data.json”
,
“w”
) as write_file:
-
json.dump(student,write_file)
-
-
with open(
“data.json”
,
“r”
) as read_file:
-
b = json.load(read_file)
-
print(b)
Output:
{'Name': 'Peter', 'Roll_no': '0090014', 'Grade': 'A', 'Age': 20}
With the dump() method, the Python object has been encoded in the file in the program that was just shown. Following that, we read the JSON file by using the load() method, to which we gave the read file parameter.
The loads() method is included in the json module, and it is used to transform JSON data to objects in the Python programming language. It is quite similar to the method known as load(). Take into consideration the following:
example:
-
Import json
-
a = [
“Mathew”
,
“Peter”
,(
10
,
32.9
,
80
),{
“Name”
:
“Tokyo”
}]
-
-
# Python object into JSON
-
b = json.dumps(a)
-
-
# JSON into Python Object
-
c = json.loads(b)
-
print(c)
Output:
['Mathew', 'Peter', [10, 32.9, 80], {'Name': 'Tokyo'}]
json.load() vs json.loads()
Loading a JSON file is done using the json.load() method, whereas loading many JSON files is done with the json.loads() function.
string.
json.dump() vs json.dumps()
The json.dump() and json.dumps() functions are used when we wish to serialize Python objects into a JSON file. The json.dump() method is also used to convert JSON data as a string for parsing and the json.dumps() function is used to convert JSON data as a string for serialization.
printing.
Python Pretty Print JSON
There are occasions when we need to inspect and troubleshoot a substantial volume of JSON data. It is possible to do this by providing the json.dumps() and json.dump functions with the extra parameters indent and sort keys ()
methods.
Note: Both dump() and dumps() functions accept indent and short_keys arguments.
Take into consideration the following:
example:
-
import
json
-
-
person =
‘{“Name”: “Andrew”,”City”:”English”, “Number”:90014, “Age”: 23,”Subject”: [“Data Structure”,”Computer Graphics”, “Discrete mathematics”]}’
-
-
per_dict = json.loads(person)
-
-
print(json.dumps(per_dict, indent =
5
, sort_keys= True))
Output:
{ "Age": 23, "City": "English", "Name": "Andrew", "Number": 90014, "Subject": [ "Data Structure", "Computer Graphics", "Discrete mathematics" ] }
The code that was just shown shows that we have given the indent parameter with 5 spaces, and that the keys have been sorted in ascending order. There is no default value for the indent property, and False is the default value for the sort key property.
.
Encoding and Decoding
The process of converting plaintext information (such as text or values) into an encrypted format is referred to as encoding. Data that has been encrypted can only be utilized by the desired user once they have decoded it. The process of encoding is sometimes referred to as serialization, while the process of decoding is also referred to as deserialization. With the JSON (object) format, both encoding and decoding are carried out. Python has a common module that may be used for these kinds of tasks. The steps below will walk us through installing it on Windows.
command:
-
pip install demjson
Encoding The encode() method is available in the demjson package, and it is used to turn a Python object into a JSON string representation. The syntax is shown here.
below:
-
demjson.encode(self,obj,nest_level =
0
)
An example of encoding by use the demjson package
-
import
demjson
-
a = [{
“Name”
:
‘Peter’
,
“Age”
:
20
,
“Subject”
:
“Electronics”
}]
-
print(demjson.encode(a))
Output:
[{"Age":20,"Name":"Peter","Subject":"Electronics"}]
Decoding – The demjson module includes the decode() method, which may be used to transform a JSON object into a format type that is compatible with Python. The syntax is shown here.
below:
-
Import demjson
-
a =
“[‘Peter’, ‘Smith’, ‘Ricky’, ‘Hayden’]”
-
print(demjson.decode(a))
Output:
['Peter', 'Smith', 'Ricky', 'Hayden']
JSON is the most efficient method to send data between a client and a web server, and that is what we have learnt about in this lesson, which is based on the Python programming language.