user3916
user3916

Reputation: 191

How can I access a list inside of a dictionary in Anible?

I have the following dictionary with a list inside (items)

{
"json": {
    "data": {
        "devices": {
            "items": [
                {
                    "configurationStatus": "SYNCED",
                    "conflictDetectionState": "IN_SYNC",
                    "connectivityState": "ONLINE",
                    "deviceType": "ASA",
                    "highAvailability": "OFF",
                    "interfaces": null,
                    "specificDevice": {
                        "namespace": "asa",
                        "type": "configs",
                        "uid": "12313131231",
                        "vpnId": null
                    },
                    "uid": "1231312313"
                }
            ],
            "metadata": {
                "count": 1
            }
        }
    }
}
}

I have registered this output under a variable called output. If I go line by line until items I can access them with no problem

    - debug:
        var: output.json
    

ok!

    - debug:
        var: output.json.data

ok!

    - debug:
        var: output.json.data.devices

ok!

    - debug:
        var: output.json.data.devices.items

ok: [localhost] => {
    "output.json.data.devices.items": "<built-in method items of dict object at 0x7f88386c8c00>"

When I come to items and want to access configurationStatus or deviceType I get the error above. I suspect its due to the items list. Any idea how could I access and register those vars?

Upvotes: 3

Views: 536

Answers (1)

larsks
larsks

Reputation: 311615

The problem is that items is the name of a method on the dictionary class, and when using . notation (foo.bar.baz), attributes get resolved before keys. So you can't access a key named items using this syntax.

Instead, try this:

    - debug:
        var: output.json.data.devices['items']

That syntax will prefer keys.

Upvotes: 5

Related Questions