Learn Python – Python JSON- Basic and advance

JSON stands for JavaScript Object Notation, which is a broadly used information format for data interchange on the web. JSON is the ideal layout for organizing records between a consumer and a server. Its syntax is comparable to the JavaScript programming language. The important objective of JSON is to transmit the facts between the patron and the internet server. It is convenient to research and the most advantageous way to interchange the data. It can be used with a number programming languages such as Python, Perl, Java, etc.

JSON by and large helps 6 kinds of data type In JavaScript:

String

Number

Boolean

Null

Object

Array

JSON is built on the two 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.

JSON statistics representation is comparable to the Python dictionary. Below is an instance of JSON data:

{  
 "book": [  
  {   
       "id": 01,  
"language": "English",  
"edition": "Second",  
"author": "Derrick Mwiti"   
],  
   {  
  {   
    "id": 02,  
"language": "French",  
"edition": "Third",  
"author": "Vladimir"   
}  
}  

Working with Python JSON

Python offers a module known as json. Python helps preferred library marshal and pickle module, and JSON API behaves similarly as these library. Python natively supports JSON features.

The encoding of JSON information is known as Serialization. Serialization is a method the place information transforms in the sequence of bytes and transmitted across the network.

The deserialization is the reverse procedure of decoding the information that is transformed into the JSON format.

This module includes many built-in functions.

Let’s have a look at these 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']

In this section, we will research the following methods:

load()

loads()

dump()

dumps()

Serializing JSON

Serialization is the method to convert the Python objects to JSON. Sometimes, laptop want to procedure plenty of statistics so it is exact to save that information into the file. We can keep JSON data into file the usage of JSON function. The json module gives the dump() and dumps() technique that are used to radically change Python object.

Python objects are transformed into the following JSON objects. The list is given 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

The dump() function

Writing JSON Data into File

Python presents a dump() function to transmit(encode) data in JSON format. It accepts two positional arguments, first is the records object to be serialized and second is the file-like object to which the bytes wants to be written.

Let’s consider the simple 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 above program, we have opened a file named data.json in writing mode. We opened this file in write mode because if the file doesn’t exist, it will be created. The json.dump() method transforms dictionary into JSON string.

The dumps () function

The dumps() feature is used to keep serialized records in the Python file. It accepts only one argument that is Python records for serialization. The file-like argument is no longer used because we aren’t not writing information to disk. Let’s consider the following 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}

JSON helps primitive records types, such as strings and numbers, as properly as nested list, tuples and 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 manner to decode the JSON records into the Python objects. The json module affords two techniques load() and loads(), which are used to convert JSON statistics in true Python object form. The list is given 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 above table indicates the inverse of the serialized desk however technically it is no longer a ideal conversion of the JSON data. It skill that if we encode the object and decode it once more after sometime; we may additionally no longer get the identical object back.

Let’s take real-life example, one man or woman interprets some thing into Chinese and any other character interprets lower back into English, and that may also now not be precisely translated. Consider the simple 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() feature is used to deserialize the JSON data to Python object from the file. Consider 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}

In the above program, we have encoded Python object in the file the use of dump() function. After that we read JSON file the usage of load() function, where we have exceeded read_file as an argument.

The json module also gives loads() function, which is used to convert JSON records to Python object. It is quite comparable to the load() function. Consider 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()

The json.load() characteristic is used to load JSON file, whereas json.loads() function is used to load string.

json.dump() vs json.dumps()

The json.dump() characteristic is used when we favor to serialize the Python objects into JSON file and json.dumps() characteristic is used to convert JSON data as a string for parsing and printing.

Python Pretty Print JSON

Sometimes we want to analyze and debug a giant amount of JSON data. It can be accomplished with the aid of passing additional arguments indent and sort_keys in json.dumps() and json.dump() methods.

Note: Both dump() and dumps() features be given indent and short_keys arguments.

Consider 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"
    ]
}

In the above code, we have supplied the 5 spaces to the indent argument and the keys are sorted in ascending order. The default fee of indent is None and the default price of sort_key is False.

Encoding and Decoding

Encoding is the approach for transforming the text or values into an encrypted form. Encrypted information can solely be used by the favored user with the aid of decoding it. Encoding is additionally known as serialization and decoding is additionally known as deserialization. Encoding and decoding are accomplished for JSON(object) format. Python offers a popular package deal for such operations. We can install it on Windows with the aid of the following command:

pip install demjson  

Encoding – The demjson bundle presents encode() feature that is used to convert the Python object into a JSON string representation. The syntax is given below:

demjson.encode(self,obj,nest_level = 0)  

Example:1 – Encoding using 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 affords decode() function, which is used to convert JSON object into Python layout type. The syntax is given below:

Import demjson  
a = "['Peter', 'Smith', 'Ricky', 'Hayden']"  
print(demjson.decode(a))  

Output:

['Peter', 'Smith', 'Ricky', 'Hayden']

In this tutorial, we have realized about the Python JSON. JSON is the most high-quality way to transmit facts between the purchaser and the net server.