Python JSON Module

JSON aka(also known as “JAVASCRIPT OBJECT NOTATION”) is a standard format for
information exchange between API’s or servers. It is a text-format and compatible with other programming languages.

JSON is portable, light-weight and works with most of the programming languages.

In Python, the JSON module is used to convert python non-primitive data types such as lists, tuples, sets and dictionary to JSON format.

We’ll call json.dumps() passing list as arguments. The method converts the list to JSON object which can be used to share data between
client and server.

import json

friends_list = [
    'John','Rambo','Sam',
]
json_format = json.dumps(friends_list)
print(json_format)
print(type(json_format))

#PYTHON OUTPUT
["John", "Rambo", "Sam"]
<class 'str'>

The output in the above example looks like a list but by checking its type we get to know that it is a string.

Syntax of json.dumps()

json.dumps(
    obj, skipkeys=False, ensure_ascii=True, check_circular=True,
    allow_nan=True, cls=None, indent=None, separators=None,
    default=None, sort_keys=False, **kw
)

For moreinfo about parameters for json.dumps() take a look at the official documentation.

Dictionary to JSON conversion

import json

cars = {
    "low_range" : [
        "maruti 800","mahindra xam"
    ],
    "medium_range" : [
        "mercedez M800", "BMW X2"
    ],
    "high_range" : [
        "Ferrari F12", "Porsche 918 spyder"
    ]
} 

_json = json.dumps(cars)

print(_json)
print(type(_json))


#PYTHON OUTPUT
{"medium_range": ["mercedez M800", "BMW X2"], "high_range": ["Ferrari F12", "Porsche 918 spyder"], "low_range": ["maruti 800", "mahindra xam"]}
<class 'str'>

Formatting JSON using separators option

The separator option helps in better representation of the JSON array. It takes a tuple with two indexes first item_separator and key_separator

syntax

json.dumps(obj,separators=(",", ":"))
j1 = json.dumps(cars,separators=(",", " : "))
j2 = json.dumps(cars,separators=(". ", " = "))
j3 = json.dumps(cars,separators=(" ; ", " == "))

print(j1)
print(j2)
print(j3)

#PYTHON OUTPUT
{"high_range" : ["Ferrari F12","Porsche 918 spyder"],"medium_range" : ["mercedez M800","BMW X2"],"low_range" : ["maruti 800","mahindra xam"]}
{"high_range" = ["Ferrari F12". "Porsche 918 spyder"]. "medium_range" = ["mercedez M800". "BMW X2"]. "low_range" = ["maruti 800". "mahindra xam"]}
{"high_range" == ["Ferrari F12" ; "Porsche 918 spyder"] ; "medium_range" == ["mercedez M800" ; "BMW X2"] ; "low_range" == ["maruti 800" ; "mahindra xam"]}

Formatting JSON array into a readable format using the indent option.

Imagine if your JSON array is multi-dimensional with hundreds of key, values and you are looking for a specific data in this case indent option in json.dumps() the method helps arrange JSON array to readable form.

j1 = json.dumps(cars, indent=4)

print(j1)

#PYTHON OUTPUT
{
    "high_range": [
        "Ferrari F12",
        "Porsche 918 spyder"
    ],
    "medium_range": [
        "mercedez M800",
        "BMW X2"
    ],
    "low_range": [
        "maruti 800",
        "mahindra xam"
    ]
}
    

Sorting JSON array using sort_keys option

Sort keys option in json.dumps() the method will sort the keys in ascending order.

We have a dictionary with keys of type integer passing this to json.dumps() method with sort_keys option specified as True.

import json

fruits = {
    2: "Apple",
    1: "Orange",
    0: "Banana",
}

j = json.dumps(fruits, indent=4, sort_keys=True)

print(j)

#PYTHON OUTPUT
{
    "0": "Banana",
    "1": "Orange",
    "2": "Apple"
}
    

Decoding JSON To Python Object

Decoding is a crucial process it helps us to fetch the data from the JSON array and then use it for some other purpose.
Most of the API’s use JSON for communication between servers which uses other server-side languages.

By decoding JSON array received from API’s we will be converting it to another datatype which can be understood by that programming language.

First, let us create a JSON array and decode that to Python datatype

import json

fruits = {
    2: "Apple",
    1: "Orange",
    0: "Banana",
}

j = json.dumps(fruits, indent=4, sort_keys=True)

decode_json = json.loads(j)

print(j)
print(type(j))
print("\n..................\n")
print(decode_json)
print(type(decode_json))

#PYTHON OUTPUT
{
    "0": "Banana",
    "1": "Orange",
    "2": "Apple"
}
<class 'str'>

..................

{'0': 'Banana', '1': 'Orange', '2': 'Apple'}
<class 'dict'>
['0', '1', '2']
    

In the above example we have a dictionary named “fruits” we have encoded it to JSON and passing the encoded JSON tp json.loads() the method will decode JSON to the dictionary we previously used to convert it.

Accessing Decoded JSON Array

The decoded object is of type dictionary and has all the property which a dictionary must-have. Hence it will be accessed by specifying a key name.

import json

fruits = {
    2: "Apple",
    1: "Orange",
    0: "Banana",
}

j = json.dumps(fruits, indent=4, sort_keys=True)

decode_json = json.loads(j)
print(decode_json['1'])

#PYTHON OUTPUT
Orange

Related Posts