I couldn’t find the answer to this anywhere online.
Does anyone know how to escape array notation when a dictionary key is passed as a parameter? My case is in Ansible, but I assume this is really a Python question.
For instance, this works:
selectattr('dict.key', 'defined')
But how would you use dict.key in array notation? Every combination of quotes and back slashes I’ve tried has failed. For instance, selectattr('dict["key"]', 'defined') does not work.
TIL though that you can escape a space in dot notation:
No, the whole thing is already in jinja brackets (I did test it though for kicks).
I have come up with a guess as to why this doesn’t work though. selectattr with array notation might result in SPNetworkDataType['Ethernet['MAC Address']'] which inherently fails, while the equivalent dot notation: SPNetworkDataType.Ethernet.MAC\ Address works simply because the syntax doesn’t wrap the keys.
I think the “correct” way to do this is probably with json_query but I was having trouble getting even a simple query to work on this for some reason…
mattiarossi@imacpro-kvm CODE % ansible-playbook a.yaml
[WARNING]: No inventory was parsed, only implicit localhost is available
[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'
PLAY [localhost] **************************************************************************************************************************************************
TASK [shell] ******************************************************************************************************************************************************
changed: [localhost]
TASK [debug] ******************************************************************************************************************************************************
ok: [localhost] => {
"msg": " ['en0']"
}
PLAY RECAP ********************************************************************************************************************************************************
localhost : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
I was copying the most simple example I could find in the documentation and it erroring out, so I’m sure I was doing something wrong on a really basic level. I’ll revisit it later.