jmespath / jmespath.py

JMESPath is a query language for JSON.

Home Page:http://jmespath.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to pass string with backslash at end to json_query

dhiraam opened this issue · comments

Below is the JSON output text from a command, trying to fetch FullName and FileVersionRaw where FullName not contains '\msvc\'

{
    "windows_result.output": [
        {
            "FullName": "E:\\\\app\\\\client\\\\product\\\\client\\\\bin\\\\file.txt",
            "Mode": "-a----",
            "Target": [],
            "VersionInfo": {
                "FileVersionRaw": "19.0.0.0",
                "ProductVersionRaw": "0.0.0.0"

            }
        },
        {
            "FullName": "E:\\\\app\\\\client\\\\product\\\\msvc\\\\vc10\\\\file.txt",
            "Mode": "-a----",
            "Target": [],
            "VersionInfo": {
                "FileVersionRaw": "19.0.0.0",
                "ProductVersionRaw": "0.0.0.0"

            }
        }
    ]
}

Below code produces result as we search only for string '\\msvc' which starts with backslash

- name: Print result - Windows
    debug:
      msg: "{{ windows_result.output | to_json | from_json | json_query(client_path) }}"
    vars:
      client_path: "[? !contains(FullName,'\\msvc')].{FullName: FullName, FileVersionRaw: VersionInfo.FileVersionRaw}"

Result output:

    "msg": [
        {
            "FileVersionRaw": "19.0.0.0",
            "FullName": "E:\\\\app\\\\client\\\\product\\\\client\\\\bin\\\\file.txt"
        }
    ]

However if string modified to '\\msvc\\' to search msvc between backslashes, \' at end considered as escape for single quote and throws error. Please help.

The reason it's failing when you add \\ to the end of the msvc is because of how it's getting rendered at the jmespath level. When you have two escapes it gets resolved to a single \, and you see in the error that there is only a single escape right after the \msvc

image

So you need to double the number of backslashes to acount for this: once for the scripting or templating language and once for the JMESPath evaluation. This will work if you change your jmespath query to "[? !contains(FullName,'\\msvc\\\\')].{FullName: FullName, FileVersionRaw: VersionInfo.FileVersionRaw}"