使用python中的请求函数解析json数据....我无法访问对象

时间:2015-01-27 09:36:14

标签: python json parsing

我的数据与此类似:

{
  "id": "694543830607034",
  "name": "Ankit Dhawan",
  "accounts": {
      "data": [
         {
            "access_token": "a",
            "category_list": [
               {
                  "id": "192119584190796",
                  "name": "Event"
               }
            ],
            "name": "Ignitron 2014", // I want to print this.
            "id": "731808386867764",
            "perms": [
               "ADMINISTER",
               "EDIT_PROFILE",
               "CREATE_CONTENT",
               "MODERATE_CONTENT",
               "CREATE_ADS",
               "BASIC_ADMIN"
            ]
         },

我也想访问页面名称(GITM-IEEE,Ignitron14), 我需要从JSON访问页面名称。

我用来尝试打印页面名称的代码:

import requests 
import json
base_url = 'https://graph.facebook.com/me'
ACCESS_TOKEN="XXXXX"
fields = 'id,name,accounts'
url = '%s?fields=%s&access_token=%s' % \
(base_url, fields, ACCESS_TOKEN,)
print url
dat = requests.get(url).json()
for a in dat:
    for b in a["data"]:
        print b["name"]

2 个答案:

答案 0 :(得分:3)

你的循环混乱了。最外面的对象是包含键的字典,这些键引用其他对象。只有最外面的data键引用的字典中的accounts键引用了一个列表。循环遍历字典会产生键(字符串),但您可以直接解决这些问题。使用嵌套在for键下的'data'列表的accounts循环:

for entry in dat['accounts']['data']:
    print entry['name']

您可以稍微清理requests代码;使用API​​来处理GET参数:

base_url = 'https://graph.facebook.com/me'
ACCESS_TOKEN="XXXXX"
params = {
    'fields': 'id,name,accounts',
    'access_token': ACCESS_TOKEN,
}
dat = requests.get(url, params=parames).json()
for entry in dat['accounts']['data']:
    print entry['name']

使用示例JSON进行演示(修复以关闭打开的对象):

>>> import json
>>> sample = '''\
... {
...     "id": "694543830607034",
...     "name": "Ankit Dhawan",
...     "accounts": {
...         "data": [
...             {
...                 "access_token": "a",
...                 "category_list": [
...                     {
...                         "id": "192119584190796",
...                         "name": "Event"
...                     }
...                 ],
...                 "name": "Ignitron 2014",
...                 "id": "731808386867764",
...                 "perms": [
...                     "ADMINISTER",
...                     "EDIT_PROFILE",
...                     "CREATE_CONTENT",
...                     "MODERATE_CONTENT",
...                     "CREATE_ADS",
...                     "BASIC_ADMIN"
...                 ]
...             }
...         ]
...     }
... }
... '''
>>> dat = json.loads(sample)
>>> for entry in dat['accounts']['data']:
...     print entry['name']
... 
Ignitron 2014

答案 1 :(得分:0)

谢谢问题解决了: 我用

import requests # pip install requests
import json
base_url = 'https://graph.facebook.com/me'
ACCESS_TOKEN="XXXXXX"
fields = 'id,name,accounts'
url = '%s?fields=%s&access_token=%s' % \
    (base_url, fields, ACCESS_TOKEN,)
dat = requests.get(url).json()
for a in dat['accounts']['data']:
    print a['name']