我反转为 'if' 语句并且代码不起作用

I invert to 'if' statement and the code don't works

我有一个 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 数据库上添加这个对象,我编写了下面的函数来完成它:

    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 变量,但这里我遇到了一些麻烦,实际上如果我 运行 这段代码第二个 ifif 'attachments' 在评论中: ) 未执行,但如果我反转两个 if 语句,代码将正确执行。为什么?

您在循环内对变量 comment 进行变异,同时对其进行迭代。这通常会导致讨厌的错误并被视为禁止。

for d in comment['data']:
            comment = d['comment']['comment']

只需将循环内的注释更改为其他内容即可。