How to parse JSON in python

JSON or JAVASCRIPT OBJECT NOTATION is now a very popular data format for using data manipulation. A JSON file is a very lightweight text file with high capacity of useful data.JSON mainly used in web-based applications. Previously XML file was used for those applications. In this article, we have learned how to parse a JSON file in python.

Parse JSON in Python

In this article, we are using very easy and simple JSON data that you can learn how much easy to do work with an external JSON file. At first, we have to need a JSON file to parse. In this example, we are using ‘sample.json’ file.

Requirements :

  • JSON python library

we are using ‘sample.json’. The JSON file contains the below JSON code:



{
    "1st_year":
    {
        "computer":
        {
            "students":"45",
            "subjects":"5",
            "faculty":"12"
        },
        "electrical":
        {
            "students":"35",
            "subjects":"6",
            "faculty":"10"
        }
        
    },
    
    
    "2nd_year":
    {
        "computer":
        {
            "students":"41",
            "subjects":"6",
            "faculty":"12"
        },
        "electrical":
        {
            "students":"31",
            "subjects":"7",
            "faculty":"10"
        }
        
    }
    
}

Now we are going to parse the ‘sample.json’ file in python :

Extract all data from JSON in python

import json

with open('sample.json') as json_file:
    data = json.load(json_file)

Or you can fetch a JSON from URL using the below code:

import requests
import json
jsn = requests.get('Your URL')
data = jsn.json()

in the ‘data’ variable we stored the whole JSON file.

print(data)

Output :

{'1st_year': {'computer': {'students': '45', 'subjects': '5', 'faculty': '12'}, 'electrical': {'students': '35', 'subjects': '6', 'faculty': '10'}}, '2nd_year': {'computer': {'students': '41', 'subjects': '6', 'faculty': '12'}, 'electrical': {'students': '31', 'subjects': '7', 'faculty': '10'}}}

 

We can find the data type of the data variable :

print(type(data))

Output :

<class 'dict'>

As we can see this variable is a Dictionary data type. Now we can perform all python dictionary operations in the data variable.

Now we can extract our user specified particular data from this dictionary variable.

Fetch particular data from JSON

print(data['1st_year'])

Output :

{'computer': {'students': '45', 'subjects': '5', 'faculty': '12'}, 'electrical': {'students': '35', 'subjects': '6', 'faculty': '10'}}

Extract from nested JSON data in python

print(data['1st_year']['computer'])
print(data['2nd_year']['computer']['students'])

Output :

{'students': '45', 'subjects': '5', 'faculty': '12'}

Leave a Reply

Your email address will not be published. Required fields are marked *