简体   繁体   English

使用Python从Facebook Graph API解析JSON字符串

[英]Parse a JSON String from Facebook Graph API using Python

I'm trying to compile all of my facebook friends user ids, but the output is difficult for me to work with. 我正在尝试编译我所有的facebook朋友用户ID,但是输出对我来说很难。 How can I simplify? 我该如何简化? It looks like this currently: 当前看起来像这样:

{
    u'friends': {
        u'paging': {
            u'next': u'https://graph.facebook.com/556702392/friends?access_token=-MYACCESSTOKEN-&limit=5000&offset=5000&__after_id=100005821213415'
        }, 
        u'data': [
            {u'name': u'Ian Fung', u'id': u'419972'}, 
            {u'name': u'Jason Turer', u'id': u'420694'},
            ...
        ]
   }
   ...
}

This is what I've been able to come up with: 这是我能够想到的:

try:
    resp = urllib2.urlopen(url)
    contents = resp.read()
except urllib2.HTTPError, error:
    contents = error.read()

json_encoded = json.loads(contents)
print json_encoded["data"]["id"]

How can I store just the IDs? 如何仅存储ID?

It's not entirely clear what data you want, but this list comprehension extracts id from friends data : 尚不清楚您想要什么数据,但是此列表idfriends data提取id

>>> json_data = {u'friends': {u'paging': {u'next': u'https://graph.facebook.com/556702392/friends?access_token=-MYACCESSTOKEN-&limit=5000&offset=5000&__after_id=100005821213415'}, u'data': [{u'name': u'Ian Fung', u'id': u'419972'}, {u'name': u'Jason Turer', u'id': u'420694'}]}}
>>> [x['id'] for x in json_data['friends']['data']]
[u'419972', u'420694']

Hope this helps you(and your given data is clumsy and not clear) 希望这对您有帮助(并且您给定的数据比较笨拙并且不清楚)

import json
from pprint import pprint

json_data=open('json_data')
decoded_data = json.load(json_data)
pprint(decoded_data)
json_data.close()

you can get the json values like this 你可以得到像这样的json值

decoded_data["friends"]["pagind"]["next"]
decoded_data["data"]["name"]
decoded_data["value"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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