I need to execute a jq query which contains double quotes. I wrapped the query in single quotes, so the double quote characters should be interpreted as normal characters. Unfortunately, jq trims them. I don't understand how and why I should escape the double quote characters.
Example: I have the test.json file:
{
  "artifacts": [
    {
      "id": "foo",
      "name": "Foo",
      "version": "1.0",
      "licenses": [
        "GPL-1",
        "GPL-2"
      ]
    },
    {
      "id": "bar",
      "name": "Bar",
      "version": "3.0",
      "licenses": [
        "GPL-3",
        "Apache 2.0"
      ]
    },
    {
      "id": "ignored",
      "name": "Ignored",
      "version": "3.0",
      "licenses": [
        "Apache 2.0"
      ]
    }
  ]
}
I would like to list all artifacts (name and version) which have at least one GPL licence. The result should be sorted alphabeticaly by name. The query to handle it is as follows:
[.artifacts[] | select(.licenses[] | startswith("GPL-"))] | unique_by(.id) | sort_by(.name) | .[] | "\(.name) \(.version)"
Unfortunately, when I execute the command it fails:
> cat .\test.json | jq -r '[.artifacts[] | select(.licenses[] | startswith("GPL-"))] | unique_by(.id) | sort_by(.name) | .[] | "\(.name) \(.version)"'
jq: error: syntax error, unexpected ')' (Windows cmd shell quoting issues?) at <top-level>, line 1:
[.artifacts[] | select(.licenses[] | startswith(GPL-))] | unique_by(.id) | sort_by(.name) | .[] | \(.name)
jq: error: syntax error, unexpected INVALID_CHARACTER (Windows cmd shell quoting issues?) at <top-level>, line 1:
[.artifacts[] | select(.licenses[] | startswith(GPL-))] | unique_by(.id) | sort_by(.name) | .[] | \(.name)
jq: 2 compile errors
The error message shows that the double quote characters are missing. I tried many combinations and I finally found the correct configuration:
> cat .\test.json | jq -r '[.artifacts[] | select(.licenses[] | startswith(""GPL-""""))] | unique_by(.id) | sort_by(.name) | .[] | """\(.name) \(.version)""'
Bar 3.0
Foo 1.0
I don't understand why I should two, next four, next three and at the end two quotes.
The query works fine on Linux:
$ cat ./test.json | jq -r '[.artifacts[] | select(.licenses[] | startswith("GPL-"))] | uniq
ue_by(.id) | sort_by(.name) | .[] | "\(.name) \(.version)"'
Bar 3.0
Foo 1.0
 
    