问题描述
我非常努力地使Windows Shell与jq一起使用,并且失败了。
I am trying really hard to get the Windows shell working with jq and failing miserably.
我想要这种类型的东西
echo '["a","b","c"]' | .\Downloads\jq.exe -r '{ "data": map({ "{#SNAME}": . })}'
但是我得到一个错误:
如果我只是做 echo'[ a, b, c]'| .\Downloads\jq.exe -r'。'
然后很高兴,但是ii还要添加其他字符,例如 echo'[ a, b , c]'| .\Downloads\jq.exe -r'{。}'
,然后再次失败:
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:
有人吗?知道如何使Windows shell对jq满意,以使上述示例能够按预期工作?
Does anyone know how to make Windows shell happy with jq for the above examples to work as expected ?
使用jq网站上的最新1.6版本进行这些测试,并确认jq命令可以使用Linux和jqplay.org。
Using latest 1.6 build from jq website for these tests and confirmed the jq commands work using Linux and jqplay.org.
谢谢。
推荐答案
您有三个主要选项:
-
(轻松)将JSON和jq程序放入单独的文件中(或者小心地放入一个文件),并相应地调用jq。
(Easy) Put the JSON and jq program into separate files (or maybe, with care, into one file), and invoke jq accordingly.
(容易出错),请遵循所用shell的引用规则。
(Error-prone) Follow the quoting rules for the shell you're using.
上述各项的组合。
我的基本规则理解如下:在Windows cmd
命令行提示符下,在orde中r引用字符串,可以使用双引号,并使用反斜杠将字符串内的双引号转义。
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.
例如:
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
同样,除了哈希和花括号外,还可以使用简单的解决方案:
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"}]}
我所用的PowerShell文档
The PowerShell documentation that I've seen suggests backticks can be used to escape special characters within double-quoted strings, but YMMV.
碰碰运气的机会!
这篇关于简单的jq筛选器无法在Windows Shell中运行,出现各种引用问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!