Home > OS >  Parsing JSON using a conditional
Parsing JSON using a conditional

Time:07-15

I'm trying to pull information from an API but only use what I need. In this case, I need to pull the "id" and "location id" if the "site id" equals a pre-defined variable.

response = {
  "results": [
    {
      "id": 92,
      "site": {
        "id": 1,
      },
      "location": {
        "id": 2,
      },
    },
    {
      "id": 196,
      "site": {
        "id": 2,
      },
      "location": {
        "id": 8,
      }
    }
  ]
}

For example, if site == 2 then get the id 196, then the location id of 8, completely ignoring the first set of data. I assume that I could do payload["results"][1]["id"] to get the ID from the second set of data, but what if it I don't know which set I need it from?

CodePudding user response:

Just iterate through them:

for result in payload["results"]:
    if result["site"]["id"] == 2:
        print(result["id"])

CodePudding user response:

results = response['results']
result_id = [r['id'] for r in results if r['site']['id'] == 2]

Output: [196]

If you are sure that the site id is unique or you only want to find the first occurence, then I would suggest to to use a break (or return if in a function) to prevent unnecessary iterations.

  • Related