使用 if then else with scan 时出现 jq 错误
jq error when using if then else with scan
我有 json:
{
"apiVersion": "projectcalico.org/v3",
"kind": "NetworkPolicy",
"metadata": {
"name": "allow-tcp-6379",
"namespace": "production"
},
"spec": {
"selector": "all()",
...
}
我select我用命令jq 'if .spec.selector == "all()" then "{}" else (scan("([0-9A-Za-z_]+) == '([0-9A-Za-z_]+)") | {(.[0]): .[1]}) end | {selector: .}'
需要的字段
但是如果我将字段更改为 .spec.selector: "app =='nginx'"
然后我得到一个错误 - jq: error (at <stdin>:39): object ({"apiVersio...) cannot be matched, as it is not a string exit status 5
如何解决这个问题?
jqplay: https://jqplay.org/s/7zS1CTHM69
您将 scan
应用于错误的对象。
if .spec.selector == "all()" then
"{}"
else
.spec.selector |
scan("([0-9A-Za-z_]+) == '([0-9A-Za-z_]+)") |
{ (.[0]): .[1] }
end
这简化为
.spec.selector |
if . == "all()" then
"{}"
else
scan("([0-9A-Za-z_]+) == '([0-9A-Za-z_]+)") |
{ (.[0]): .[1] }
end
你在一个路径中输出一个字符串而在另一个路径中输出一个对象似乎很奇怪。这是正确的吗?
除了没有指定你想要从三个备选方案(all()
、x == 'y'
、其他)中得到什么,你也没有指定整个程序的输出是什么,所以不清楚这是怎么回事应该纳入您的计划。
我有 json:
{
"apiVersion": "projectcalico.org/v3",
"kind": "NetworkPolicy",
"metadata": {
"name": "allow-tcp-6379",
"namespace": "production"
},
"spec": {
"selector": "all()",
...
}
我select我用命令jq 'if .spec.selector == "all()" then "{}" else (scan("([0-9A-Za-z_]+) == '([0-9A-Za-z_]+)") | {(.[0]): .[1]}) end | {selector: .}'
但是如果我将字段更改为 .spec.selector: "app =='nginx'"
然后我得到一个错误 - jq: error (at <stdin>:39): object ({"apiVersio...) cannot be matched, as it is not a string exit status 5
如何解决这个问题?
jqplay: https://jqplay.org/s/7zS1CTHM69
您将 scan
应用于错误的对象。
if .spec.selector == "all()" then
"{}"
else
.spec.selector |
scan("([0-9A-Za-z_]+) == '([0-9A-Za-z_]+)") |
{ (.[0]): .[1] }
end
这简化为
.spec.selector |
if . == "all()" then
"{}"
else
scan("([0-9A-Za-z_]+) == '([0-9A-Za-z_]+)") |
{ (.[0]): .[1] }
end
你在一个路径中输出一个字符串而在另一个路径中输出一个对象似乎很奇怪。这是正确的吗?
除了没有指定你想要从三个备选方案(all()
、x == 'y'
、其他)中得到什么,你也没有指定整个程序的输出是什么,所以不清楚这是怎么回事应该纳入您的计划。