Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Parsing JSON using a conditional

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Just iterate through them:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading