1

How to extract an element from JSON file by element name? For example what I have in the ansible-playbook:

- debug:
    msg: "{{ test }}"

This is output (my file)

ok: [test] => {
    "msg": [
        {
            "element1": {
                "test1": "test3",
                "test2": [
                    "1",
                    "2",
                    "3"
                ],
                "info": {
                    "test4": "test",
                    "test": 1,
                    "test": "test"
                },
                "test": "test",
                "test": "test",
                "test": "test",
                "test": "test"
            },
            "element2": {
                "test": "test",
                "test": [
                    "test",
                    "test"
                ],
                "test": {
                    "test": "test",
                    "test": 1,
                    "test": "test",
                    "test": 1
                },
                "test": "test",
                "test": "test",
                "test": "test",
                "test": "test"
            }
        }
    ]
}

I need to create a filter to get only element1 by his name

- name: Get item by name
  debug: msg="{{ my_json_file | json_query(jmesquery) }}"
  vars:
    jmesquery: "[?contains(@, `element2`)]"

And expect to get output like

"element1": {
    "test1": "test3",
    "test2": [
        "1",
        "2",
        "3"
    ],
    "info": {
        "test4": "test",
        "test": 1,
        "test": "test"
    },
    "test": "test",
    "test": "test",
    "test": "test",
    "test": "test"
}
β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
Veneomin
  • 31
  • 3

1 Answers1

2

In JMESPath, basic querying of an element based on a key is as simple as specifying the key, see basic querying.

So, in your case, the correct JMESPath query would simply be:

[].element2

And, so, in your task:

 - name: Get item by name
   debug: 
     msg: "{{ my_json_file | json_query(jmesquery) }}"
   vars:
     jmesquery: "[].element2"

This said, Ansible is based on YAML, which is a superset of JSON, so your task can as well be achieved in a way easier manner:

 - name: Get item by name
   debug: 
     msg: "{{ my_json_file.0.element2 }}"
β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83