Home > Net >  Python : How to loop through data to access similar keys present inside nested dict
Python : How to loop through data to access similar keys present inside nested dict

Time:04-06

I have an API, after calling which I'm getting a very big json in response. I want to access similar keys which are present inside the nested dict. I'm using following lines to make a get request and storing the json data : -

    p25_st_devices = r'https://url_from_where_im_getting_data.com'

    header_events = {
           'Authorization': 'Basic random_keys'}

    r2 = requests.get(p25_st_devices, headers= header_events)
    r2_json = json.loads(r2.content)

The sample of the json is as follows : -

{
    "next": "value",
    "self": "value",
    "managedObjects": [
        {
            
            "creationTime": "2021-08-02T10:48:15.120Z",
            "type": " c8y_MQTTdevice",
            "lastUpdated": "2022-03-24T17:09:01.240 03:00",
            "childAdditions": {
                "self": "value",
                "references": []
            },
            "name": "PS_MQTT1",
            "assetParents": {
                "self": "value",
                "references": []
            },
            "self": "value",
            "id": "338",
            "Building": "value"
        },
        {
           
            "creationTime": "2021-08-02T13:06:09.834Z",
            "type": " c8y_MQTTdevice",
            "lastUpdated": "2021-12-27T12:08:20.186 03:00",
            "childAdditions": {
                "self": "value",
                "references": []
            },
            "name": "FS_MQTT2",
            "assetParents": {
                "self": "value",
                "references": []
            },
            "self": "value",
            "id": "339",
            "c8y_IsDevice": {}
        },
        {
            
            "creationTime": "2021-08-02T13:06:39.602Z",
            "type": " c8y_MQTTdevice",
            "lastUpdated": "2021-12-27T12:08:20.433 03:00",
            "childAdditions": {
                "self": "value",
                "references": []
            },
            "name": "PS_MQTT3",
            "assetParents": {
                "self": "value",
                "references": []
            },
            "self": "value",
            "id": "340",
            "c8y_IsDevice": {}
        }
    ],
    "statistics": {
        "totalPages": 423,
        "currentPage": 1,
        "pageSize": 3
    }
}

As per my understanding I can access name key using r2_json['managedObjects'][0]['name'] But how do I iterate over this json and store all values of name inside an array?

EDIT 1 :

Another thing which I'm trying to achieve is get all id from the JSON data and store in an array where the nested dict managedObjects contains name starting with PS_ only. Therefore, the expected output would be device_id = ['338','340']

CodePudding user response:

You should not just call the [0] index of the list, but loop over it:

all_names = []
for object in r2_json['managedObjects']:
    all_names.append(object['name'])
print(all_names)

edit: Updated answer after OP updated theirs.

For your second question you can use startswith(). The code is almost the same.

PS_names = []
for object in r2_json['managedObjects']:
    if object['name'].startswith("PS_"):
        PS_names.append(object['id']) # we append with the id, if startswith("PS_") returns True.

print(PS_names)
  • Related