[Tutor] json file

Kent Johnson kent37 at tds.net
Sun Feb 14 04:39:25 CET 2010


On Sat, Feb 13, 2010 at 3:00 PM, Chris Patillo <pythonnewbie6 at gmail.com> wrote:
> Thanks for your response.  i did some research on json.load() and I don't
> understand how you extract the data from it.  How do I get just the name and
> number from the file?

The value returned from json.load() is a Python dictionary. The
structure of the dict will be the same as that of your initial data.
In your case, the value of the 'records' key is itself a list of dicts
containing names and phone numbers. To get the desired data you have
to navigate this structure using standard python.

Here is an example using your sample data. Note that I use
json.loads() because I have the data in a string, rather than a file.

import json
from pprint import pprint

json_data = '''{
   "table":"contacts",
   "records":[
      {
         "name":"John",
         "phone":"555-555-4444"
      },
      {
         "name":"Jane",
         "phone":"555-555-3333"
      }
   ]
}'''

data = json.loads(json_data)
pprint(data)

for record in data['records']:
    print record['name'], record['phone']

The output of the program is

{u'records': [{u'name': u'John', u'phone': u'555-555-4444'},
              {u'name': u'Jane', u'phone': u'555-555-3333'}],
 u'table': u'contacts'}
John 555-555-4444
Jane 555-555-3333

Kent

PS Please Reply All to reply on list.


More information about the Tutor mailing list