Search code examples
pythonazure-devops-rest-api

Python get value form a list of object


I'm making a request call with python but I'm struggling to retrieve the data that I need from the Json.

here the Json:

{
    "count": 987,
    "value": [
        {
            "quality": "definition",
            "drafts": [],
            "queue": {
                "_links": {
                    "self": {
                        "href": "https://myUrl/"
                    }
                },
                "id": 987551,
                "name": "something",
                "url": "https://myUrl/",
                "pool": {
                    "id": 81,
                    "name": "myProjectName"
                }
            },
            "id": 477,
            "name": "myProjectName",
            "url": "https://myUrl/",
            "uri": "",
            "path": "\\",
            "type": "build",
            "queueStatus": "enabled",
            "revision": 18,
            "createdDate": "2020-07-03T09:06:01.6Z"
        },

        {
            //another object similar to the above one

        },
...
    ]
}

and this is what I'm trying:

response = requests.get(organization_url, auth=basic, headers=headers)

test = response.json()
print(test['value'][0])

with the code above I'm able to print the first object of my value, and I have no problem accessing the "queue" object using something like

print(test['value'][0]['queue'])

But I cannot understand how I can print the id or the name tha are outside the queue object

            "id": 477,
            "name": "myPersonalProjectName",

If I try something

print(test['value'][0]['name'])

I get:

KeyError: 'name'

I have also tried to iterate but I'm missing something. From my understanding, the value object should be a list with different dict inside and others key:value.

But why something like this doesn't work?

print(test['value'][0]['name'])

Thanks!


Solution

  • Thanks all for your reply guys,

    as always it was my bad! It seems that somehow I took the wrong Json from the request that I was doing. And python was right, there isn't a key called name in my Json, or there is, but it's more nested.

    So, something like

    print(test['value'][0]['name'])
    

    is not working because in correct JSON, at position [0], 'name' is not there, but

    print(test['value'][0]['definition']['name'])
    

    I'm almost sure that I copied the Json wrongly, and I could not figure out why my script was not working. So I made a call with postman, and start searching for the field that I was looking for, and then I found that it was more nested.

    Thanks!