Python和JSON语法问题

2024-04-25 00:54:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我对TwitchAPI JSON的措辞有问题。我正在尝试阅读name,它位于多个层下(不确定正确的术语)

以下是API JSON的一部分:

{
"_links": {
    "next": "https://api.twitch.tv/kraken/channels/test_user/follows?direction=DESC&limit=25&offset=25",
    "self": "https://api.twitch.tv/kraken/channels/test_user/follows?direction=DESC&limit=25&offset=0"
},
"_total": 336,
"follows": [
    {
        "_links": {
            "self": "https://api.twitch.tv/kraken/users/test_follower/follows/channels/test_user"
        },
        "created_at": "2014-07-24T20:21:10Z",
        "user": {
            "_id": 00000001,
            "_links": {
                "self": "https://api.twitch.tv/kraken/users/test_follower"
            },
            "bio": null,
            "created_at": "2014-07-05T17:27:45Z",
            "display_name": "test_follower",
            "logo": null,
            "name": "test_follower",
            "type": "user",
            "updated_at": "2014-07-24T20:20:29Z"
        }
    },

等等,它继续使用我希望收集的多个name

如何获取name项?这是我目前的尝试

print [data['name'] for data in data['follows']['user']]

但这只是给出了一个错误TypeError: list indices must be integers, not str

提前谢谢!你知道吗


Tags: namehttpstestselfapidatalinkstv
2条回答

我认为这是这样的:

print [data['name'] for data in data['follows']]

我希望这有帮助

data['follows']list,不能使用['user']获取此列表中的元素。 您需要一个循环或使用data['follows'][0]来获取

{
    "_links": {
        "self": "https://api.twitch.tv/kraken/users/test_follower/follows/channels/test_user"
    },
    "created_at": "2014-07-24T20:21:10Z",
    "user": {
        "_id": 00000001,
        "_links": {
            "self": "https://api.twitch.tv/kraken/users/test_follower"
        },
        "bio": null,
        "created_at": "2014-07-05T17:27:45Z",
        "display_name": "test_follower",
        "logo": null,
        "name": "test_follower",
        "type": "user",
        "updated_at": "2014-07-24T20:20:29Z"
    }
}

所以,data['follows'][0]['user']会得到你

"user": {
        "_id": 00000001,
        "_links": {
            "self": "https://api.twitch.tv/kraken/users/test_follower"
        },
        "bio": null,
        "created_at": "2014-07-05T17:27:45Z",
        "display_name": "test_follower",
        "logo": null,
        "name": "test_follower",
        "type": "user",
        "updated_at": "2014-07-24T20:20:29Z"
    }

然后在它后面附加[name],以获得用户名。你知道吗

所以答案是:print data['follows'][0]['user']['name']

或者

print [data['user']['name'] for data in data['follows']]

即使将data['follows']['user']更改为data['follows'][0]['user']for循环也不正确,因为data['name']无效。你知道吗

=====我不能对答案发表评论======

另一个答案是不正确的,因为在data['follows']中没有'name'

相关问题 更多 >