parsing JSON data with Python

How To Parse JSON File Content Using Python

In this blog, you will learn to parse JSON file using a Python script.

When it comes to day to day Python based DevOps work, parsing files is a common task. So it is essential to know how to parse JSON using Python.

Parse JSON using Python

Consider a scenario where you have to do the following using python.

  1. Read a JSON file from a path, parse it and print a specific value.
  2. Get a JSON from a remote URL (API call etc ) and parse it.

This article covers both the above scenarios.

Example JSON:

Following simple JSON is used as an example for this tutorial.

{
    "name" : "test",
    "ip" : "198.168.23.45",
    "country" : "United States",
    "project" : "Data Analytics",
    "website" : "scriptscrunch.com"
}

Read a JSON file from a path and parse it

In this scenario, you have a JSON file in some location in your system and you want to parse it.

You need to have the JSON module to be imported for parsing JSON.

The sample code is given below.

import json
json = json.loads(open('/path/to/file.json').read())
value = json['key']
print json['value']

You need to replace /path/to/file.json with the relative path of the JSON file.

json = json.loads(open('/path/to/file.json').read())

To get a value from the JSON file, all you need to use the key with json keyword. For example, country from the example JSON file.

value = json['country']

Here is a complete example script where we use JSON and os python module to retrieve the absolute path of the JSON file. Also, we are using for loop to print all the keys and values of the JSON file.

import json
import os

# Script to create absolute path of the JSON file.

script_dir = os.path.dirname(__file__)
print("The Script is located at:" + script_dir )
script_absolute_path = os.path.join(script_dir, 'example.json')
print("The Script Path is:" + script_absolute_path)

# Script to parse JSON

json = json.loads(open(script_absolute_path).read())
value = json['name']
print(value)

# Loop through JSON keys and values

for key in json:
    value = json[key]
    print("The key and value are ({}) = ({})".format(key, value))

Get a JSON from a remote URL (API Request) and parse it

In this scenario, you have a JSON response from a remote file or a API call and you want to parse it.

You need to have json and urllib2 modules for this.

Here is the sample code to do this.

import urllib2
import json
req = urllib2.Request("http://jsonplaceholder.typicode.com/todos/1")
opener = urllib2.build_opener()
f = opener.open(req)
json = json.loads(f.read())
print json
ip = json['id']
print json['id']

Loop Through JSON Objects

You can also loop through all the JSON objects. You just need to add the following for loop to your code.

json object will hold the actual JSON content.

# print the keys and values
for key in json:
    value = json[key]
    print("The key and value are ({}) = ({})".format(key, value))

Full code will look like the following.

import json
json = json.loads(open('/path/to/file.json').read())
value = json['key']
print json['value']

# print the keys and values
for key in json:
    value = json[key]
    print("The key and value are ({}) = ({})".format(key, value))

Conclusion

In this blog, we learned how to parse a JSON file using python.

Python knowledge is essential for developers, DevOps engineers, and data engineers. Check out the python for devops blog, where I have explained how python is used in DevOps and why it is essential for DevOps engineers.

Other Interesting Blogs

2 thoughts on “How To Parse JSON File Content Using Python”

Leave a Comment

Share via
Copy link
Powered by Social Snap