How to search for specific value in Json array using Python

Your code can be simplified a lot:

# no need to call `r.json` so many times, can simply save it to a variable
json_data = r.json()
for item in json_data["data"]["array"]:
    if item["name"] == "Value1":
        # do something...

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!')

Here is a one-liner example for searching:

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

[a['name'] for a in aaa['data']['array'] if a['id']=='1']

This will return all the found cases, or an empty array if nothing is found

Tags:

Python

Json