keytab
keytab

Reputation: 11

Accessing fields that contain a special character in json_query

How to access a field with a special character with ansible filter json_query? Example of json input:

{
    "list": [{
        "name": "ZZZ",
        "_id": {
            "$oid": "5ba3c813c2dc4bf8392f8ec0"
        }
    }]
}

My example code:

- name: "Display all cluster names"
  debug:
    msg: "{{ result.json.list | json_query(\"[?name=='ZZZ']._id.$oid\") }}"

But fail with the next message:

fatal: [localhost]: FAILED! => {"msg": "JMESPathError in json_query filter plugin:\nBad jmespath expression: Unknown token $:\n[?name=='ZZZ']._id.$oid\n                       ^"}

Upvotes: 1

Views: 1004

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68074

If the name comprises special characters it's possible to quote the attribute. For example

- hosts: localhost
  vars:
    list:
      - name: "ZZZ"
        _id:
          $oid: "5ba3c813c2dc4bf8392f8ec0"
  tasks:
    - debug:
        msg: "{{ list|json_query(query) }}"
      vars:
        query: "[?name=='ZZZ']._id.\"$oid\""

gives

"msg": [
    "5ba3c813c2dc4bf8392f8ec0"
]

Upvotes: 1

Related Questions