Find the value of at a specific part in JSON with Python

Viewed 30

I am having a code like:

myvar0 = jsonfromapi['people']['young']['data'][0][information][isreal]
myvar1 = jsonfromapi['people']['young']['data'][1][information][isreal]
myvar2 = jsonfromapi['people']['young']['data'][2][information][isreal]

print(myvar0)
print(myvar1)
print(myvar2)

Output:

true
false
false

Now the JSON includes a lot of 'people'. But every time only one of them is true real. My goal is to only print the data from the one that is true. In my example above 0. Unfortunately the true one changes. Sometimes it's 0 who is true, sometimes 1 and sometimes 2. How can I only get the true one and get more data from this true one? For example, when 2 is true: myvar2 = jsonfromapi['people']['young']['data'][2][information][name] but without the names of 1 and 0.

EDIT: Every time only one person is real / true.

2 Answers

Assuming you use Python, you should probably loop through the list in jsonfromapi['people']['young']['data'].

real_person = None
for I, _ in enumerate(jsonfromapi['people']['young']['data']):
    if jsonfromapi['people']['young']['data'][i][information][isreal]:
        real_person = jsonfromapi['people']['young']['data'][i]

Finally, you can check if real_person is not None just to be sure that there is at least one real person. If there is more than 1 real, then this will return the last one found. For retrieving the first, you should add a break after the if check. If you want to get all the real persons, you can create a list and append everything there. Hope this answers your question.

As there is only a single person with the true value, you could simply do:

real_person = next(data for data in jsonfromapi['people']['young']['data'] if data[information][isreal])
Related