How to Parse JSON in Python

How do we parse JSON in Python. First we load a JSON file using json.load() method. The result is a Python dictionary. We can then access the fields using dictionary methods.

JSON is a lightweight data-interchange format.

To extract information from a JSON file or a JSON response, we have to parse the data.

Parse JSON in Python

We will use the following JSON in our example:

{
   "store":{
      "book":[
         {
            "category":"reference",
            "author":"Nigel Rees",
            "title":"Sayings of the Century",
            "price":8.95
         },
         {
            "category":"fiction",
            "author":"Evelyn Waugh",
            "title":"Sword of Honour",
            "price":12.99
         }
      ],
      "bicycle":{
         "color":"red",
         "price":19.95
      }
   },
   "expensive":10
}

The first step is to load the JSON file in Python:

import json

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

The JSON file is now stored in the data variable.

The print method will just print the above JSON.

Extract Particular Data From JSON

Now that we have our JSON as a Python dictionary, we can fetch certain data by specifying the field, which represents the key in the dictionary.

For example, to fetch the price of the bicycle in the above JSON, we would use:

print(data['store']['bicycle']['price'])

Output:

19.95

Extract Data From JSON Array

In the above JSON example, the “book” field is a JSON Array.

We can use the index notation to fetch particular items.

For example, to get the name of the second book we would use:

print(data['store']['book'][1]['title'])

Output:

Sword of Honour

Conditional Parsing of JSON

Suppose we wanted to get all the books which have price less than or equal to 10.00.

Then we would use:

books = data['store']['book']
for book in books:
    if book['price'] <= 10.00:
        print(book)

Output:

{'category': 'reference', 'author': 'Nigel Rees', 'title': 'Sayings of the Century', 'price': 8.95}

Conclusion

In this post we looked at how to parse JSON in Python. The key takeaway here is that once the JSON file is loaded, it is stored as a Python dictionary. Once we have the dictionary, we can then use the normal dictionary methods to extract specific values from JSON.