0

I'm iterating over a JSON object, then adding each result I get to an array but for each result that gets added to the array, they array is then cleared then it moves down the list of results.

Here's what I mean: enter image description here

Here's the code I used to get this issue:

for e in loadedJson['posts']['entities']:
  print(e)
  titles = []
  titles.append(e)
  print(titles)
4
  • 2
    you are clearing the array on this line titles = [] in each iteration. So what's the problem? Commented Aug 26, 2020 at 17:11
  • Move titles=[] before the loop, that's it Commented Aug 26, 2020 at 17:12
  • Oh, yeah sorry I completely didn't realise what I did. Thanks! Commented Aug 26, 2020 at 17:13
  • 1
    The array is cleared because you say so. Read this article for tips on debugging your code. Commented Aug 26, 2020 at 17:13

1 Answer 1

3

Try to move titles outside the loop

titles = []
for e in loadedJson['posts']['entities']:
  print(e)
  titles.append(e)
print(titles)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.