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

后端 未结 1 653
时光取名叫无心
时光取名叫无心 2021-01-21 05:11

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\"]\'          


        
1条回答
  •  无人共我
    2021-01-21 06:03

    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!

    0 讨论(0)
提交回复
热议问题