JSON Library

In this tutorial we learn about JSON file creation ,access the file.JSON stands for the JavaScript Object Notation is the famous data format it is the lightweight file which is used for storing the data into the file.

Module import

import json

Create JSON file

import json

person_info = {'Name': 'Amit','Age': 12,'Language': '[Hindi,English]'}
with open('personinfo.json', 'w') as jsonfile:
  json.dump(person_info, jsonfile)

JSON file load

Program 1

import json 
f= open('personinfo.json',) 
data = json.load(f) 
print(data)
f.close()

Output

C:\Users\ASUS\Desktop>python abc.py
{'Name': 'Amit', 'Age': 12, 'Language': '[Hindi,English]'}

Program 2

import json 
f= open('personinfo.json',) 
data = json.load(f) 
print(data['Language'])
f.close()

Output

[Hindi,English]

Parse JSON- Convert from JSON to Python

If you have a json string,you can parse it by using the json.dump() method.

Convert from json to Python

Program

import json
data =  '{ "Name":"Rahul", "Age":22, "Education":"B.Tech"}'
parse= json.loads(data)
print(parse["Education"])

Output

C:\Users\ASUS\Desktop>python abc.py
B.Tech

Convert from Python to Json

import json
data={
  "Name": "Rahul",
  "Age": 22,
  "Education": "B.Tech"
}		#dictionary

parse = json.dumps(data)
print(parse)

Output

C:\Users\ASUS\Desktop>python abc.py
{"Name": "Rahul", "Age": 22, "Education": "B.Tech"}

You can convert Python objects of the following type in json string.

  1. Dictionary
  2. List
  3. Tuple
  4. String
  5. Int
  6. Float
  7. True
  8. False
  9. None
import json

a=json.dumps({"Name": "Amit", "Age": 23})	
print(type({"Name": "Amit", "Age": 23}),a)
b=json.dumps(["Reema", "Seema"])	
print(type(["Reema", "Seema"]),b)	
c=json.dumps(("Apple", "Guava"))	
print(type(("Apple", "Guava")),c)	
d=json.dumps("Hello World")		
print(type("Hello World"),d)
e=json.dumps(100)			
print(type(100),e)
f=json.dumps(22.22)
print(type(22.22),f)
g=json.dumps(True)		
print(type(True),g)
h=json.dumps(False)		
print(type(False),h)
i=json.dumps(None)	
print(type(None),i)

Output

 {"Name": "Amit", "Age": 23}
 ["Reema", "Seema"]
 ["Apple", "Guava"]
 "Hello World"
 100
 22.22
 true
 false
 null

When we convert the from Python to json then python objects also converted into Json(Javascript)

Python Data Type JSON
dict object
list array
string String
tuple array
int Number
float Number
True true
False false
None null

Program

import json

data = {
  "Name": "Divya",
  "Age": 21,
  "Educated": True,
  "Job": False,
  "Language": ("English","Hindi"),
  "Vehicle": None,
  "Degree": [
    {"B.tec": "First Division", "Percentage": 74.5},
    {"Stream": "Computer Science"}
  ]
}

print(json.dumps(data))

Output

{"Name": "Divya", "Age": 21, "Educated": true, "Job": false, "Language": ["English", "Hindi"], "Vehicle": null, "Degree": [{"B.tec": "First Division", "Percentage": 74.5}, {"Stream": "Computer Science"}]}

Printing the value with proper indent

import json

data = {
  "Name": "Divya",
  "Age": 21,
  "Educated": True,
  "Job": False,
  "Language": ("English","Hindi"),
  "Vehicle": None,
  "Degree": [
    {"B.tec": "First Division", "Percentage": 74.5},
    {"Stream": "Computer Science"}
  ]
}

print(json.dumps(data,indent=5))

Output

{
      "Name": "Divya",
      "Age": 21,
      "Educated": true,
      "Job": false,
      "Language": [
            "English",
            "Hindi"
      ],
      "Vehicle
": null,
      "Degree": [
            {
                  "B.tec": "First Division",
                  "Percentage": 74.5
            },
            {
                  "Stream": "Computer Science"
            }
      ]
}

C:\Users\ASUS\Desktop>

Printing the value with separator

import json

data = {
  "Name": "Divya",
  "Age": 21,
  "Educated": True,
  "Job": False,
  "Language": ("English","Hindi"),
  "Vehicle": None,
  "Degree": [
    {"B.tec": "First Division", "Percentage": 74.5},
    {"Stream": "Computer Science"}
  ]
}

print(json.dumps(data,indent=6, separators=(". ", " = ")))

Output

C:\Users\ASUS\Desktop>python abc.py
{
      "Name" = "Divya".
      "Age" = 21.
      "Educated" = true.
      "Job" = false.
      "Language" = [
            "English".
            "Hindi"
      ].
      "Vehicle" = null.
      "Degree" = [
            {
                  "B.tec" = "First Division".
                  "Percentage" = 74.5
            }.
            {
                  "Stream" = "Computer Science"
            }
      ]
}

Sort by the key

import json

data = {
  "Name": "Divya",
  "Age": 21,
  "Educated": True,
  "Job": False,
  "Language": ("English","Hindi"),
  "Vehicle": None,
  "Degree": [
    {"B.tec": "First Division", "Percentage": 74.5},
    {"Stream": "Computer Science"}
  ]
}

print(json.dumps(data,indent=6, sort_keys=True))

Output

C:\Users\ASUS\Desktop>python abc.py
{
      "Age": 21,
      "Degree": [
            {
                  "B.tec": "First Division",
                  "Percentage": 74.5
            },
            {
                  "Stream": "Computer Science"
            }
      ],
      "Educated": true,
      "Job": false,
      "Language": [
            "English",
            "Hindi"
      ],
      "Name": "Divya",
      "Vehicle": null
}
Subscribe Now