[Fixed]-Django – Extract from JSON data using Python

0👍

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']
👤Nurdin

1👍

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"])

0👍

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.

Leave a comment