How to parse JSON in Python?


JSON (JavaScript Object Notation) is a lightweight data format used to interchange the data. It is human-readable and can be easily parsed and generated by machines. JSON is a text format that is independent of language.

This format of data is most commonly used to transmit and receive data between a web application and a server. In this article, we will discuss how to read, write and parse JSON in Python programming.

Example of JSON data format

The following example shows the JSON data format. Let’s say the name of this file is data.json, now see data inside it.

{
   "students":[
      {
         "roll_no":"1",
         "name":"John",
         "total_marks":"67"
      },
      {
         "roll_no":"2",
         "name":"Ritesh",
         "total_marks":"83"
      },
      {
         "roll_no":"3",
         "name":"Vandna",
         "total_marks":"78"
      }
   ]
}

In a JSON file, the pair of names and values are separated using a colon, while each pair is separated by a comma. Curly braces hold the objects and the square bracket holds an array with comma-separated values.

Import JSON module in Python

Python has a built-in package called json to work with JSON data. First, you need to import this module if you want to use it.

import json

Parse JSON in Python

A JSON string can be parsed by using json.loads() method in Python. This method returns a Python dictionary after parsing data.

You can see the usage of json.loads() method in the given example.

import json

# JSON string
student_json ='{"roll_no":"02", "name": "Ritesh", "total_marks":"83"}'
# Convert JSON string to Python dict
student_dict = json.loads(student_json)
print(student_dict)
print(student_dict['name'])

Save this file and execute it. Now you can see the output of this code in the image below.

Read a JSON file in Python

By using json.load() method you can read a JSON file in Python. You can see this in the example below.

import json

with open("data.json") as f:
    data = json.load(f)
    for i in data["students"]:
       print(i)

When you execute this code you will see the following output.

Convert a Python dictionary to JSON string

A Python object can be converted to JSON using the json.dumps() method. You can see the usage of this method in the example below.

import json
# Python dictionary
student_dict = {'roll_no': '1', 'name': 'John', 'total_marks': '67'}
# Convert dictionary to JSON
student_json = json.dumps(student_dict)
print(student_json)

When you save and execute this code you will see the given output.

The following type of Python objects can be converted to JSON you can see the type of object and their equivalent JSON –

Convert and write JSON to a file

Python provides a method called json.dump() to write JSON to a file. Now see the given example.

import json

# Data to be written
student_dict ={
"roll_no" : 10,
"name" : "Harshit",
"total_marks": 73,
}

with open("student.json", "w") as outfile:
json.dump(student_dict, outfile)

This code will write JSON to student.json file you can find this file in your current working directory.

Conclusion

Now I hope you understand what is a JSON file and how to parse it in Python. If you have a query then write us in the comments below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.