Flo Woo
Flo Woo

Reputation: 989

Simple jq filters not working in Windows shell, various quoting issues

I am trying really hard to get the Windows shell working with jq and failing miserably.

I want this type of thing to work

echo '["a","b","c"]' | .\Downloads\jq.exe -r '{ "data": map({ "{#SNAME}": . })}'

But I get an error:

jq: error: syntax error, unexpected '.' (Windows cmd shell quoting issues?) at , line 1:

If i just do echo '["a","b","c"]' | .\Downloads\jq.exe -r '.' then it's happy but as soon i i add in other characters such as echo '["a","b","c"]' | .\Downloads\jq.exe -r '{.}' then it fails again with:

jq: error: syntax error, unexpected '.' (Windows cmd shell quoting issues?) at , line 1:

Does anyone know how to make Windows shell happy with jq for the above examples to work as expected ?

Using latest 1.6 build from jq website for these tests and confirmed the jq commands work using Linux and jqplay.org.

Thank you.

Upvotes: 6

Views: 9554

Answers (1)

peak
peak

Reputation: 116880

You have three main options:

  1. (Easy) Put the JSON and jq program into separate files (or maybe, with care, into one file), and invoke jq accordingly.

  2. (Error-prone) Follow the quoting rules for the shell you're using.

  3. Some combination of the above.

The basic rule as I understand it is as follows: at a Windows cmd command-line prompt, in order to quote strings, you use double-quotes, and escape double-quotes within the string using backslashes.

For example:

C>ver
Microsoft Windows [Version 10.0.17134.590]

C>echo "hello \"world\"" | jq .
"hello \"world\""

C>jq -n "\"hello world\""
"hello world"

Your example

C>echo ["a","b","c"] | jq -c "{\"data\":map({\"{#SNAME}\":.})}"
{"data":[{"{#SNAME}":"a"},{"{#SNAME}":"b"},{"{#SNAME}":"c"}]}

Postscript

Except for the hash (#) and braces ({}) in the string, one can achieve the goal by avoiding spaces:

C>echo ["a","b","c"] | jq -c {"data":map({"SNAME":.})}
{"data":[{"SNAME":"a"},{"SNAME":"b"},{"SNAME":"c"}]}

Powershell

Again, except for the hash and braces, simple solutions are possible:

Using single-quoted strings:

 echo '["a", "b", "c"]' | jq -c '{"data": map( {"SNAME": . })}'
 {"data":[{"SNAME":"a"},{"SNAME":"b"},{"SNAME":"c"}]}

Using "" inside double-quoted strings:

echo '["a", "b", "c"]' | jq -c "{""data"": map( {""SNAME"": . })}"
{"data":[{"SNAME":"a"},{"SNAME":"b"},{"SNAME":"c"}]}

The PowerShell documentation that I've seen suggests backticks can be used to escape special characters within double-quoted strings, but YMMV.

Bonne chance!

Upvotes: 10

Related Questions