Search code examples
pythonneo4jcypherpy2neo

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


I have a JSON file where the objects are in this form:

{
  "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."
},

but not everyone has the key 'url'. I'm tring to add this objects on a neo4j db using py2neo and I wrote the function below to do it:

    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

For testing, I'm just printing the url variable, but here I have some troubles, in fact if I run this code the second if (if 'attachments' in comment: ) is not executed, but if I invert the two if statement the code is correctly execute. Why?


Solution

  • You mutate the variable comment inside the loop while iterating on it. This usually cause nasy bugs and considered as forbidden.

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

    Just change the comment inside the loop to something else.