How to simply access an object in a JSON with keys which are integers?

Viewed 41

I have this example:

---
- hosts: localhost   
  gather_facts: false   
  
  vars:
    json1: {'disk_info': {'A': {'label': 'Hard disk 1'}, 'B': {'label': 'Hard disk 2'}}}
    json2: {'disk_info': {'0': {'label': 'Hard disk 1'}, '1': {'label': 'Hard disk 2'}}}   
  
  tasks:
  
  - debug: msg="{{json1.disk_info.A}}"

  - debug: msg="{{item.value.label}}"
    loop: "{{ lookup('dict', json2.disk_info) }}"
    when: "'0' in item.key"

Is it possible to access json 1.disk_info.0 the same way as json 2.disk_info.A - i.e. without a lookup on a dict?

1 Answers

Yes it is perfectly possible. But you have to play a bit to make sure your key name is read as a string containing your digit, and not interpreted as an integer index of a list.

Because of this the following will fire an error:

json2.disk_info.0
json2.disk_info[0]

Therefore, the correct syntax for your data structure is:

json2.disk_info['0']
Related