4

What is the correct way to loop through the following json object?

test = [{
    'start': 'ieo5',
    'end': 'tiu9',
    'chain': 10489
}, {
    'start': 'qvc5',
    'end': 'tiu9',
    'chain': 45214
}, {
    'start': 'ieo5',
    'end': 'tiu9',
    'chain': 69296
}]

I essentially want to loop through and print out whatever the value of start is.

I've tried a bunch of options like the ones listed here but can't seem to get it to work.

This doesn't work:

for x in test
    print x['start'] 
6
  • 1
    Use print(x['start']) instead. Python 3 needs parentheses in print calls. Commented Nov 12, 2018 at 5:18
  • 1
    Also, : at the end of for line. Commented Nov 12, 2018 at 5:20
  • add column(:) after test in for loop statement Commented Nov 12, 2018 at 5:20
  • 1
    What you have there is not a JSON array. It is a Python structure of a list of dictionaries. Commented Nov 12, 2018 at 5:23
  • 1
    :), yes you are correct Commented Nov 12, 2018 at 5:38

3 Answers 3

5

Your code logic works fine, just few things making it not work:

  • Since the tag is , print needs to be called.

  • Need colon after for line.

So the code would look like:

for x in test:
    print(x['start'])
Sign up to request clarification or add additional context in comments.

Comments

1

worked for me!

for d in test:
     print d['start']

OP:

ieo5
qvc5
ieo5

Comments

1

The syntax is right just add a colon after the for statement

for x in test:
    print(x['start'])

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.