blindy blindy - 1 year ago 63
JSON Question

How do I pull a recurring key from a JSON in python?

I'm new to python (and coding in general), I've gotten this far but I'm having trouble. I'm querying against a web service that returns a json file with information on every employee. I would like to pull just a couple of attributes for each employee, but I'm having some trouble.

I have this script so far:

import json
import urllib2

req = urllib2.Request('')
response = urllib2.urlopen(req)
the_page =

j = json.loads(the_page)

print j[1]['name']

The JSON that it returns looks like this...

"name": bill jones,
"address": "123 something st",
"city": "somewhere",
"state": "somestate",
"zip": "12345",
"phone_number": "800-555-1234",
"name": jane doe,
"address": "456 another ave",
"city": "metropolis",
"state": "ny",
"zip": "10001",
"phone_number": "555-555-5554",

You can see that with the script I can return the name of employee in index 1. But I would like to have something more along the lines of: print j[0 through len(j)]['name'] so it will print out the name (and preferably the phone number too) of every employee in the json list.

I'm fairly sure I'm approaching something wrong, but I need some feedback and direction.

Thanks in advance.

Answer Source

Your JSON is the list of dict objects. By doing j[1], you are accessing the item in the list at index 1. In order to get all the records, you need to iterate all the elements of the list as:

for item in j:
    print item['name']

where j is result of j = json.loads(the_page) as is mentioned in your answer

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download