Search code examples
pythonjsonapiparsingyahoo-api

Parse JSON in Python Issue


I am currently working with the yahoo api.

I am able to retrieve a json response from the api call. I am trying to parse this data in python and am currently having trouble.

Here are the process I am doing that is not parsing correctly and getting an error.

resp.content - this holds the JSON message - the json looks like below

{"query":{"count":1,"created":"2015-09-22T19:52:42Z","lang":"en-US","results":{"player":{"player_key":"348.p.4256","name":{"full":"Peyton Manning"}}}}}

Following Steps

 >>> import json
 >>> parsed_json = json.loads(resp.content)

I am wanting to only extract and print Peyton Manning

>>> print(parsed_json['full'])

When I run the print line: I receive this error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'full'

Does anyone know what I am doing wrong in this example.


Solution

  • You have a nested dictionary; dictionaries whose values are other dictionaries.

    Using the pprint.pprint() function would make this clearer:

    >>> from pprint import pprint
    >>> pprint(parsed_json)
    {u'query': {u'count': 1,
                u'created': u'2015-09-22T19:52:42Z',
                u'lang': u'en-US',
                u'results': {u'player': {u'name': {u'full': u'Peyton Manning'},
                                         u'player_key': u'348.p.4256'}}}}
    

    You need to address the keys along a path to get the value for the 'full' key:

    >>> parsed_json['query']['results']['player']['name']['full']
    u'Peyton Manning'