Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pull a recurring key from a JSON?

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('http://server.company.com/api')
response = urllib2.urlopen(req)
the_page = response.read()

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.

like image 983
blindy Avatar asked Sep 21 '16 00:09

blindy


People also ask

How do I iterate keys in JSON?

Use Object. keys() to get keys array and use forEach() to iterate over them.

Can JSON have repeated keys?

We can have duplicate keys in a JSON object, and it would still be valid. The validity of duplicate keys in JSON is an exception and not a rule, so this becomes a problem when it comes to actual implementations.

Can JSON have multiple keys with same name?

There is no "error" if you use more than one key with the same name, but in JSON, the last key with the same name is the one that is going to be used. In your case, the key "name" would be better to contain an array as it's value, instead of having a number of keys "name".

Can a JSON object be a key?

Since JSON can only be contained in strings in JS, you can use JSON as key. E.g. var obj = {'{"foo": 42}': "bar"}; . If you mean a JS object, no, that's not possible. You can use objects as keys, but they're converted into strings.

Does JSON syntax allow duplicate keys in an object?

The short answer: Yes but is not recommended. The long answer: It depends on what you call valid...


2 Answers

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

like image 186
Moinuddin Quadri Avatar answered Sep 23 '22 00:09

Moinuddin Quadri


Slightly nicer for mass-conversions than repeated dict lookup is using operator.itemgetter:

from future_builtins import map  # Only on Py2, to get lazy, generator based map
from operator import itemgetter

for name, phone_number in map(itemgetter('name', 'phone_number'), j):
    print name, phone_number

If you needed to look up individual things as needed (so you didn't always need name or phone_number), then regular dict lookups would make sense, this just optimizes the case where you're always retrieving the same set of items by pushing work to builtin functions (which, on the CPython reference interpreter, are implemented in C, so they run a bit faster than hand-rolled code). Using a generator based map isn't strictly necessary, but it avoids making (potentially large) temporary lists when you're just going to iterate the result anyway.

It's basically just a faster version of:

for emp in j:
    name, phone_number = emp['name'], emp['phone_number']
    print name, phone_number
like image 21
ShadowRanger Avatar answered Sep 24 '22 00:09

ShadowRanger