Mikey
Mikey

Reputation: 107

Is this JSON data parsed into Python dict correctly?

Cannot extract components of data parsed from JSON to Python dictionary.

I attempted to print the value corresponding with a dictionary entry but get an error.

import urllib, json, requests
url = "https://storage.googleapis.com/osbuddy-exchange/summary.json"
response = urllib.urlopen(url)
data = json.loads(response.read())

print type(data)

for key, value in data.iteritems():
    print value
print ''

print "data['entry']: ", data['99']

print "name: ", data['name']```

I was hoping I could get attributes of an entry. Say the 'buy_average' given a specific key. Instead I get an error when referencing specific components.

<type 'dict'>
22467 {u'sell_average': 3001, u'buy_average': 0, u'name': u'Bastion potion(2)', u'overall_average': 3001, u'sp': 180, u'overall_quantity': 2, u'members': True, u'sell_quantity': 2, u'buy_quantity': 0, u'id': 22467}
22464 {u'sell_average': 4014, u'buy_average': 0, u'name': u'Bastion potion(3)', u'overall_average': 4014, u'sp': 270, u'overall_quantity': 612, u'members': True, u'sell_quantity': 612, u'buy_quantity': 0, u'id': 22464}
5745 {u'sell_average': 0, u'buy_average': 0, u'name': u'Dragon bitter(m)', u'overall_average': 0, u'sp': 2, u'overall_quantity': 0, u'members': True, u'sell_quantity': 0, u'buy_quantity': 0, u'id': 5745}
...
data['entry']:  {u'sell_average': 7843, u'buy_average': 7845, u'name': u'Ranarr potion (unf)', u'overall_average': 7844, u'sp': 25, u'overall_quantity': 23838, u'members': True, u'sell_quantity': 15090, u'buy_quantity': 8748, u'id': 99}
name: 
Traceback (most recent call last):
  File "C:/Users/Michael/PycharmProjects/osrsGE/osrsGE.py", line 16, in <module>
print "name: ", data['name']
KeyError: 'name'

Process finished with exit code 1

Upvotes: 0

Views: 48

Answers (1)

balderman
balderman

Reputation: 23815

There is no key named 'name' in the dict named 'data'. The first level keys are numbers like: "6", "2", "8",etc The seconds level object has a key named 'name' so code like:

print(data['2']['name']) # Cannonball

should work

Upvotes: 1

Related Questions