【发布时间】:2017-08-09 17:11:01
【问题描述】:
我目前正在使用 Python 和 Facebook Graph API。
我需要解析从 Facebook Graph API 检索到的信息,我想知道哪种方法是最好的方法。
当然,
r = json.loads(request)
将解析 JSON 并生成字典。
当我需要访问嵌套字典时,问题就来了,例如
ob["data"][0]["reactions"]["data"][0]
假设我们正在解析 Facebook 帖子,如果帖子没有反应,这当然会失败,因为字典中甚至不存在该键。
if 'comments' not in dct and 'summary' not in dct and 'total_count' not in dct:
dct["comments"] = {"summary": {"total_count": -1}}
作为一个临时解决方案,我最终做了这样的事情,创建“默认值”,这样架构就永远不会中断,并且能够读取图中的任何节点而不会出错。
你们怎么看?怎样才能做得更好?
编辑:
class post(DynamicDocument):
def __init__(self, *dct, **tmp):
Document.__init__(self, **tmp)
if dct:
....
self.totalComentarios = dct["comments"]["summary"]["total_count"]
【问题讨论】:
-
使用
d.get(desc, default value)。也许您可以添加一些示例 JSON 以使此解决方案的应用更加清晰。 -
只需将其包装在
try块中并捕获 KeyError/IndexError? -
问题是我有这样的东西:CHECK EDIT ON POST 并且拥有 dct.get("cmets", {}") 是不够的,我需要对每个级别都执行此操作,在这种情况下也对摘要和总数执行此操作,但还有更深层次的情况。
-
使用这种方法:[链式get()方法](stackoverflow.com/q/45077397/7414759)
标签: python json facebook dictionary facebook-graph-api