Kevin C
Kevin C

Reputation: 5720

Ansible and JMESPath, escape forward slash in a json_query

There is a simple JSON file, sample.json with the following content:

{
  "test": {
    "domain": [
      {
        "name": "cluster1"
      }
    ]
  }
}

With Ansible, I want to query over the test key, which works with the following Ansible playbook.

---
- hosts: localhost
  vars:
    tmpdata: "{{ lookup('file','sample.json') | from_json }}"

    - debug:
        msg: "{{ tmpdata | json_query('test') }}"

The play

ok: [localhost] => {
    "msg": {
        "domain": [
            {
                "name": "cluster1"
            }
        ]
    }
}

However, when they key in the JSON file is changed, from test to test/something, and the ansible json_query from test to test/something as well, Ansible/JMESPath produces an error.

fatal: [localhost]: FAILED! => {"msg": "JMESPathError in json_query filter plugin:\nBad jmespath expression: Unknown token /:\ntest/something\n    ^"}

I've looked into the JMESpath documentation, but it does not make sense to me.

How can I ensure JMESpath works with forward slashes in the Ansible query.

Upvotes: 4

Views: 5111

Answers (1)

Konstantin Suvorov
Konstantin Suvorov

Reputation: 68229

JMESPath defines identifier as unquoted-string / quoted-string.

unquoted-string is A-Za-z_. Anything else should be quoted.

In your case:

- debug:
    msg: "{{ tmpdata | json_query('\"test/something\"') }}"

Here we escape \" because we are inside YAML double quotes msg: "...".

Upvotes: 4

Related Questions