Shailee Shah Shailee Shah - 1 year ago 77
Python Question

extracting data from json using python

Extracting Data from JSON

The program will prompt for a URL, read the JSON data from that URL using urllib and then parse and extract the comment counts from the JSON data, compute the sum of the numbers in the file.

Sample data: http://python-data.dr-chuck.net/comments_42.json (Sum=2553)

Data Format
The data consists of a number of names and comment counts in JSON as follows:

{
comments: [
{
name: "Matthias"
count: 97
},
{
name: "Geomer"
count: 97
}
...
]
}


Basically , json file reads to be a dictionary . the second element of the dictionary is a list. now this list has dictionaries in it. i need to find values from them.

My code where i am stuck at is:

import json
import urllib
total = 0

url='http://python-data.dr-chuck.net/comments_42.json'
uh=urllib.urlopen(url).read()
info =json.loads(uh)
for items in info[1]:
#print items
print items[1:]

Answer Source

You could try:

import json
import urllib 
total = 0

url='http://python-data.dr-chuck.net/comments_42.json'
uh=urllib.urlopen(url).read()
info =json.loads(uh)
count_values = [ el['count'] for el in info['comments'] ] 
name_values = [ el['name'] for el in info['comments'] ] 
print count_values
print name_values

output of count_values:

[97, 97, 90, 90, 88, 87, 87, 80, 79, 79, 78, 76, 76, 72, 72, 66, 66, 65, 65, 64, 61, 61, 59, 58, 57, 57, 54, 51, 49, 47, 40, 38, 37, 36, 36, 32, 25, 24, 22, 21, 19, 18, 18, 14, 12, 12, 9, 7, 3, 2]

output of name_values:

[u'Romina', u'Laurie', u'Bayli', u'Siyona', u'Taisha', u'Alanda', u'Ameelia', u'Prasheeta', u'Asif', u'Risa', u'Zi', u'Danyil', u'Ediomi', u'Barry', u'Lance', u'Hattie', u'Mathu', u'Bowie', u'Samara', u'Uchenna', u'Shauni', u'Georgia', u'Rivan', u'Kenan', u'Hassan', u'Isma', u'Samanthalee', u'Alexa', u'Caine', u'Grady', u'Anne', u'Rihan', u'Alexei', u'Indie', u'Rhuairidh', u'Annoushka', u'Kenzi', u'Shahd', u'Irvine', u'Carys', u'Skye', u'Atiya', u'Rohan', u'Nuala', u'Maram', u'Carlo', u'Japleen', u'Breeanna', u'Zaaine', u'Inika']
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download