Loading, please wait...

A to Z Full Forms and Acronyms

Python JSON| Python tutorial

This article is all about JSON, serialization, deserialization, formatting the json results and order of the result.

Python JSON

JSON stands for JavaScript Object Notation. It is a standardized format that is commonly used to transfer data as text that can be sent over the network. JSON represents objects as name/value pairs, just like a Python Dictionary. It is used by lots of APIs and databases because it is easy for both humans and machines to read. JSON is a built-in package that can be used to work with JSON data.

We can start learning JSON by importing the built-in JSON module.

Syntax:

import json

Before using this module we must know the two terms which are Serialization and another is Deserialization.

Serialization: In python, the process of converting data into JSON format is known as Serialization. Now, let’s discuss how to serialize the JSON data.

Serializing JSON data:

There are two methods for serializing Python objects into a JSON format.

1. dump(): This method can be used when we need to serialize python data to an external JSON file. This method will write the python data to the file-like object.

2. dumps(): This method can be used if you want to use the JSON in our program or to print it on the console. This method will write Python data to a string in JSON format.

One thing we must know that python and JSON don’t have the same datatype.

While serialization the python objects will be converted into following JSON Objects.

 PYTHON         JSON

  dict           -> object

  list, tuple   -> array

  str            -> string

 int, long, float ->     number

 True -> true

 False -> false

 None -> null  

Example: Convert Python object into JSON format.

#convert from JSON to python
import json
#json
student= '{ "name": "MK" , "rollno": 39, "marks" = 99 }'
#parsing student:
y= json.loads(student)

#the result is a python dictionary:
print(y["marks"])
#output: 99

Deserialization: In python, the process of converting JSON data back into a native object is known as Deserialization.

Like serialization, there are two methods in the JSON module that helps to deserialize the data.

1. load():  This method load JSON data from a file-like object.

2. loads():  This method load JSON data from a string containing JSON-encoded data.

Note: these methods return a Python ‘dict’ or ‘list’ containing deserialized data.

How JSON data is deserialized into python objects

JSON                PYTHON

Object          -> dict

Array           -> list

String          -> str

Number(int) -> int

Number(real) -> float 

true             -> True 

false            -> False

null              -> None

Example: Convert JSON data to Python object:

#convert from  python dict to JSON string
import json
#python dictionary
student= { 'name' : 'MK',
    "rollno": 39,
    "marks" : 99 }
#converting into JSON:
y= json.dumps(student)

#the result is a JSON string:
print(y)
#output:
{ 'name' : 'MK', "rollno": 39, "marks" : 99 }

example:

#all python objects into json string
print(json.dumps(["java", "php" ,"lisp"]))
#["java", "php" ,"lisp"]
print(json.dumps({"emp": "KUMAR" , "age" :34}))
#{"emp": "KUMAR" , "age" :34}
print(json.dumps(("java", "python")))
#["java", "python"]
print(json.dumps('welcome'))
#'welcome'
print(json.dumps(89))
#89
print(json.dumps(0.111))
#0.111
print(json.dumps(True))
#true
print(json.dumps(False))
#false
print(json.dumps(None))
#null

Note: Serialization and Deserialization are not perfectly inverse operation.

Let’s understand this through an example if we serialize a python tuple then it will become an json array. But after deserialization json array will result in a list containing data of tuple. If we want tuple back then we have to use a tuple constructor.

 Formatting the result

 We can format the result after serialization and deserialization.

 There are two ways that we can use to format the result.

 1. use of indent:

 After printing a python object into a JSON string, it is difficult to read the string, with no indentation and line breaks. so to make it readable we can use the indent parameter to define the number of indents.

json.dumps( i, indent=2)

 

2. use of separator:

 By default, the separator value is a comma and a space to separate each object, and a colon and a space to separate keys from values.

Now, let’s see how we can change the default separator.

Json.dump(i,indent=3,seperators= (“. ”, “ = ”))

How to ensure the order of results?

 We can use the sort_key parameter to specify if the result is sorted or not.

json.dumps(i , indent=3, sort_key =True)

Thanks for reading this article, hope you like it...

A to Z Full Forms and Acronyms

Related Article