简体   繁体   中英

Extract data from JSON in python

Can I access link inside next from the below Json data? I am doing in this way

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

Because comments is a main object. Inside the comments there are three sub objects data , paging and summary . The above code is doing the same , inside comments , because of paging is an object of multiple other objects, in the loop and print that. It is giving the error

for h in i['paging']: TypeError: string indices must be integers

    "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"
}

You're iterating through "comments" which results in three objects: data , paging , and summary . All you want is paging , but your first for-loop wants you to go through all the others.

Thus, when it starts with data , you're trying to call data['paging'] , but this doesn't work because data 's value is a list and not a dictionary.

You want to immediately access paging :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM