Json in Python

Q : Why we need Data Representation Format?
If the data in a data file is not sorted, then we will not understand the data in that data file.
So we need data representation format.

There are many formats of data representation :
                                      ➤ CSV
                                      ➤ XML
                                       JSON

Nowadays JSON is very popular. JSON is JavaScript Object Notation. JSON is data representation format. JSON is formatted sting.

Q : Why we use JSON, Why it's important?
For this we need to understand how data is exchanged on the web. Data is exchanged on the web by protocol. Example : HTTP, FTP, TCP etc. 
The protocols for exchanging data in the web only understands text. Text are summation of string. In other words, Which sent by protocols or receive by protocols all are small or large string. JSON file also contains all the strings.

JSON format :            
                '{
                        "Name" : "Anik",
                        "ID" : "18101073",
                        "Semester" : "3-2"
                }'

JSON data format is pair of key and value. Here key = "Name" and value = "Anik".

JSON is look like Python Dictionary. The Basic Different of JSON and Dictionary is JSON doesn't support comment but Dictionary support comment.

JSON support five data type. They are : 
                                ➤ Array  [ In python : Dictionary, list, tuple ]
                                ➤ Boolean
                                ➤ Number
                                ➤ Object
                                ➤ String 

# Now we see some Built-in-function in JSON

# json.loads() here "loads" mean "load string". This function first read hole json string then it convert dictionary data type.

import json

x = '{ "name" : "anik", "age" : 14, "id" : 73 }'

y = json.loads(x)

print("JSON to Dictionary : ", y)

Output :  JSON to Dictionary :  {'name': 'anik', 'age': 14, 'id': 73}


# json.dumps() This fucntion convert Dictionary data type to JSON string format.

import json

info = {
"name" : "anik",
"id" : "18101073",
"semester" : "3-2"
}

y = json.dumps(info)

print("Dictionary of JSON : ", y)

➤ Output Dictionary of JSON :  {"name": "anik", "id": "18101073", "semester": "3-2"}

# Nested Dictionary data type to JSON string format.

import json

information = {
"student1":
{
"Name": "Dani Daniels",
"ID": 18101072,
"Semester": "3-2"
},
"student2":
{
"Name": "Aubdur Rob Anik",
"ID": 18101073,
"Semester": "3-2"
},
"student3":
{
"Name": "Sophie Dee",
"ID": 18101074,
"Semester": "3-2"
}
}

y = json.dumps(information)

print("Dictionary of JSON : ", y)

➤ Output Dictionary of JSON :  {"student1": {"Name": "Dani Daniels", "ID": 18101072, "Semester": "3-2"}, "student2": {"Name": "Aubdur Rob Anik", "ID": 18101073, "Semester": "3-2"}, "student3": {"Name": "Sophie Dee", "ID": 18101074, "Semester": "3-2"}}

# For Output pretty print here use indent parameter. indent parameter specifies the spaces that are used at the beginning of a line.

import json

information = {
"name" : "anik",
"id" : 73,
"age" : "18+",
"married" : True,
"children" : ("Rafiq", "Oni"),
"cars" : [
{
"model" : "TATA Nano XM624",
"price" : "100tk"
},
{
"model" : "BMW 230",
"price" : "450tk"
}
]
}

y = json.dumps(information, indent = 4)

print("Dictionary of JSON : ", y)

➤ Output :
Dictionary of JSON :  {
    "name": "anik",
    "id": 73,
    "age": "18+",
    "married": true,
    "children": [
        "Rafiq",
        "Oni"
    ],
    "cars": [
        {
            "model": "TATA Nano XM624",
            "price": "100tk"
        },
        {
            "model": "BMW 230",
            "price": "450tk"
        }
    ]
}

# Here we use "separators" parameter,  separators = (". ", " = ") which means using a "." and a space to separate each object and (space -> equal to -> space) to separate keys from values.

import json

information = {
"name" : "anik",
"id" : 73,
"age" : "18+",
"married" : True,
"children" : ("Rafiq", "Oni"),
"cars" : [
{
"model" : "TATA Nano XM624",
"price" : "100tk"
},
{
"model" : "BMW 230",
"price" : "450tk"
}
]
}

y = json.dumps(information, indent = 4, separators = (". ", " = "))

print("Dictionary of JSON : ", y)

➤ Output :   
Dictionary of JSON :  {
    "name" = "anik". 
    "id" = 73. 
    "age" = "18+". 
    "married" = true. 
    "children" = [
        "Rafiq". 
        "Oni"
    ]. 
    "cars" = [
        {
            "model" = "TATA Nano XM624". 
            "price" = "100tk"
        }. 
        {
            "model" = "BMW 230". 
            "price" = "450tk"
        }
    ]
}

# Here use "sort_keys" parameter. It use for sort the key in the JSON format.

import json

information = {
"name" : "anik",
"id" : 73,
"age" : "18+",
"married" : True,
"children" : ("Rafiq", "Oni"),
"cars" : [
{
"model" : "TATA Nano XM624",
"price" : "100tk"
},
{
"model" : "BMW 230",
"price" : "450tk"
}
]
}

y = json.dumps(information, indent = 4, separators = (". ", " = "), sort_keys = True)

print("Dictionary of JSON : ", y)

➤ Output : 

Dictionary of JSON :  {
    "age" = "18+". 
    "cars" = [
        {
            "model" = "TATA Nano XM624". 
            "price" = "100tk"
        }. 
        {
            "model" = "BMW 230". 
            "price" = "450tk"
        }
    ]. 
    "children" = [
        "Rafiq". 
        "Oni"
    ]. 
    "id" = 73. 
    "married" = true. 
    "name" = "anik"
}

# JSON Format data write in a file and read from a file.

info = {}

info['person1'] = {
"name" : "anik",
"age" : "18+",
"id" : 73
}

info['person2'] = {
"name" : "sabuj",
"age" : "20",
"id" : 51
}

info['person3'] = {
"name" : "atik",
"age" : "19",
"id" : 64
}

import json
str = json.dumps(info, indent=4)

f = open('jsonfile.txt', 'w')
f.write(str)
f.close()

f = open('jsonfile.txt', 'r')
str = f.read()
print("JSON Format : ", str)

➤ Output :   
JSON Format :  {
    "person1": {
        "name": "anik",
        "age": "18+",
        "id": 73
    },
    "person2": {
        "name": "sabuj",
        "age": "20",
        "id": 51
    },
    "person3": {
        "name": "atik",
        "age": "19",
        "id": 64
    }
}

# JSON Apply on List 

import json
lst = ["anik", "oni", "rafiq", "jotti", "saifi"]

str = json.dumps(lst)
print("List to json : ", lst)

➤ Output List to json :  ['anik', 'oni', 'rafiq', 'jotti', 'saifi']

# JSON Apply on Tuple

import json
tuple = ("anik", "ononna", "ritu", "puspo")

str = json.dumps(tuple)
print("tuple to json : ", tuple)

➤ Output tuple to json :  ('anik', 'ononna', 'ritu', 'puspo')

Comments