我有一个JSON文件,其中对象的格式如下:
{
"timestamp": 1568811686,
"attachments": [
{
"data": [
{
"external_context": {
"url": "https://media2.giphy.com/media/ce1ARlVo9jPdhwbOKL/v1.Y2lkPTEyMGMwMTQ3NTRjOGMwMjc2MTU2NzE5NmRiODQ5NzY5MTEyN2JmMmZmZTMwNjg3Mg/giphy-downsized.gif"
}
}
]
}
],
"title": "Name Surname ha commentato il post di Name Surname."
},
但并非每个人都有键“ url”。我正在尝试使用py2neo将这个对象添加到neo4j db上,我编写了以下函数:
for comment in comments['comments']:
if 'data' in comment:
group = ''
for d in comment['data']:
comment = d['comment']['comment'].encode('latin1')
if 'group' in d['comment']:
group = d['comment']['group'].encode('latin1')
if group == '':
node = Node('Comment', timestamp=timestamp, title=title, comment=comment_text)
else:
node = Node('Comment', timestamp=timestamp, title=title, comment=comment_text, group=group)
graph.create(node)
if 'attachments' in comment:
for attachments in comment['attachments']:
for d in attachments['data']:
if 'external_context' in d:
url = d['external_context']['url']
print url
为了进行测试,我只是打印 url 变量,但是这里有些麻烦,实际上,如果我在第二个 if < / strong>(如果注释中为“附件” ) 未执行,但是如果我将两个if语句反转,则代码将正确执行。为什么?
答案 0 :(得分:1)
您可以在循环内对变量comment
进行迭代。通常会导致讨厌的错误,因此被认为是禁止的。
for d in comment['data']:
comment = d['comment']['comment']
只需将循环内的注释更改为其他内容即可。