parsing JSON data with Python

How To Parse JSON File Content Using Python

Scenario: Consider you have to do the following using python.

  1. Read a JSON file from a path and parse it.
  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.

value = json['key']

[alert-success]

Recommended Courses

The Python Bible™ | Everything You Need to Program in Python

Complete Python Bootcamp: Go from zero to hero in Python 3

[/alert-success]

Get a JSON from a remote URL and parse it

In this scenario, you have a JSON response from a remote file 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))
parsing JSON data with Python

Other Interesting Blogs

Leave a Comment

0 Shares
Share via
Copy link