Reputation: 23883
Everytime I extract from JSON data, I will got TypeError: unhashable type: 'dict'
My json info
u 'paging': {
u 'cursors': {
u 'after': u 'MTQyNzMzMjE3MDgxNzUzOQZDZD', u 'before': u 'OTUzNDg3MjMxMzQ2NjQ0'
}
}, u 'data': [{
u 'access_token': u 'XXXXX',
u 'category': u 'Internet/Software', u 'perms': [u 'ADMINISTER',
u 'EDIT_PROFILE', u 'CREATE_CONTENT', u 'MODERATE_CONTENT',
u 'CREATE_ADS', u 'BASIC_ADMIN'
], u 'name': u 'Nurdin Norazan Services', u 'id': u '953487231346644'
}, {
u 'access_token': u 'XXXXX',
u 'category': u 'Internet/Software', u 'perms': [u 'ADMINISTER',
u 'EDIT_PROFILE', u 'CREATE_CONTENT', u 'MODERATE_CONTENT',
u 'CREATE_ADS', u 'BASIC_ADMIN'
], u 'name': u 'Intellij System Solution Sdn. Bhd.', u 'id': u '433616770180650'
}]
}
My code
data = json.load(urllib2.urlopen("https://graph.facebook.com/v2.7/me/accounts?access_token="XXXXX")
print (data[data][0][id]) //953487231346644
Incidentally, how to print loop data?
Upvotes: 0
Views: 944
Reputation: 23883
I just got the answer
data = json.load(urllib2.urlopen("https://graph.facebook.com/v2.7/me/accounts?access_token="XXXXX")
for i in data['data']:
print i['id']
Upvotes: 0
Reputation: 6039
According to the docs, json.load
is for reading file pointers (or some object that implements the read()
interface).
https://docs.python.org/2.7/library/json.html#json.load
I'd say you want json.loads
, but in fact you want json.dumps
. Your TypeError implies that you are getting in a python dictionary (very similar to JSON), whereas json.load/s expects a string.
>>> import json
>>> json.dumps({"foo": "bar"})
'{"foo": "bar"}'
>>> json.loads({"foo": "bar"})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python3.4/json/__init__.py", line 312, in loads
s.__class__.__name__))
TypeError: the JSON object must be str, not 'dict'
>>> json.loads(json.dumps({"foo": "bar"}))
{'foo': 'bar'}
As for looping through data, iterate through it:
for key, val in data.items():
print("{}: {}".format(key, val))
You may have to implement some fancier looping if you want to recursively loop through json.
Upvotes: 0
Reputation: 599470
Your problem is not in "extracting" the data: it's your print statement, as the full traceback would have shown.
In that statement for some reason you call data[data]
. But that just means you're trying to index the data dictionary with itself. To get the data key, you need to use a string: data["data"]
; and the same for the id value.
print(data["data"][0]["id"])
Upvotes: 1