Zach Long Zach Long - 1 year ago 57
Python Question

How to search for specific value in Json array using Python

I'm using a website's

API
to get information. It outputs 100 values.

What is the best practice of searching for a specific value in this array?

The array looks something like this:

{
"success":true,
"data":
{
"array":
[
{
"id":"1","name":"Value1"
},
{
"id":"2","name":"Value2"
}
]
}
}


I try searching for the data using this snippet I found elsewhere, however it does not work:

for name in (r.json()['data']['array'][0]['name']):
if r.json()['data']['array'][0] == s_name:
ident = r.json()['data']['array'][0]['id']
name = r.json()['data']['array'][0]['name']
print (name + ' - ' + ident)
else:
print ('Nothing was found.')


So if I was trying to reference
Value1
how would I do this using
Python
?

Please note: I'm a rookie developer, first time using
Json
, not very experienced with
Python
.

All help is greatly appreciated.

Answer Source

Not sure where that piece of code came from but it looks very wrong.

Just looking at the structure you can do something like:

for attrs in r.json()['data']['array']:
    if attrs['name'] == s_name:
        ident = attrs['id']
        name = attrs['name']
        print(name + ' - ' + ident)
        break
else:
    print('Nothing found!')