How do I pull a recurring key from a JSON?
<p>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.</p>

<p>I have this script so far:</p>

<pre><code>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']
</code></pre>

<p>The JSON that it returns looks like this...</p>

<pre><code>{
    "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",
},
</code></pre>

<p>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: <code>print j[**0 through len(j)**]['name']</code> so it will print out the name (and preferably the phone number too) of every employee in the json list.</p>

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

<p>Slightly nicer for mass-conversions than repeated <code>dict</code> lookup is using <a href="https://docs.python.org/3/library/operator.html#operator.itemgetter" rel="nofollow"><code>operator.itemgetter</code></a>:</p>

<pre><code>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
</code></pre>

<p>If you needed to look up individual things as needed (so you didn't always need <code>name</code> or <code>phone_number</code>), then regular <code>dict</code> 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 <code>map</code> isn't strictly necessary, but it avoids making (potentially large) temporary <code>list</code>s when you're just going to iterate the result anyway.</p>

<p>It's basically just a faster version of:</p>

<pre><code>for emp in j:
    name, phone_number = emp['name'], emp['phone_number']
    print name, phone_number
</code></pre>

python json