从python中的JSON中提取数据

时间:2016-09-11 09:16:26

标签: python json

我可以从以下next数据中访问Json内的链接吗?我这样做了

data = json.loads(html.decode('utf-8'))
for i in data['comments']:
        for h in i['paging']:
            print(h)
{

因为comments是主要对象。在comments内,有三个子对象datapagingsummary。上面的代码在comments内执行相同的操作,因为paging是多个其他对象的对象,在循环和打印中。它给出了错误

  

for h in i ['paging']:   TypeError:字符串索引必须是整数

    "comments": {
        "data": [
            {
                "created_time": "2016-05-22T14:57:04+0000",
                "from": {
                    "id": "908005352638687",
                    "name": "Marianela Ferrer"
                },
                "id": "101536081674319615443",
                "message": "I love the way you talk! I can not get enough of your voice. I'm going to buy Seveneves! I'm going to read it this week. Thanks again se\u00f1or Gates. I hope you have a beautiful day:-)"
            }
        ],
        "paging": {
            "cursors": {
                "after": "NzQ0",
                "before": "NzQ0"
            },
            "next": "https://graph.facebook.com/v2.7/10153608167431961/comments?access_token=xECxPrxuXbaRqcippFcrwZDZD&summary=true&limit=1&after=NzQ0"
        },
        "summary": {
            "can_comment": true,
            "order": "ranked",
            "total_count": 744
        }
    },
    "id": "10153608167431961"
}

1 个答案:

答案 0 :(得分:1)

您正在遍历“评论”,这会产生三个对象:datapagingsummary。你想要的只是paging,但你的第一个for-loop希望你经历所有其他的。

因此,当它以data开头时,您尝试调用data['paging'],但这不起作用,因为data的值是列表而不是字典。

您想立即访问paging

print data['comments']['paging']['next']