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

parsing json data using request function in python.... i am unable to access the objects

我的数据是这样的:

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

你的循环搞混了。您最外层的对象是一个包含键的字典,这些键引用更多的对象。只有最外层 accounts 键引用的字典中的 data 键引用了一个列表。遍历字典只产生键(字符串),但您可以直接处理这些键。对嵌套在 accounts 键下的 'data' 列表使用 for 循环:

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

感谢问题已解决: 我用

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