Jq:步行时测试场地
Jq: testing a field during walk
考虑以下 jq 配置:
walk
(
if (type == "object" and .key | test("something")) then
del(.)
else
.
end
)
以及以下 JSON:
[
{
"key": "something",
"value": "something"
},
{
"key": "another thing",
"value": "another thing"
},
{
"key": "something",
"value": "something"
}
]
但是,jq 抛出以下错误:
jq: error (at :13): boolean (false) cannot be matched, as it is not a string
13 是输入的最后一行。它试图匹配什么布尔值?
这里一般不需要walk()
。我会像这样使用 map()
:
jq 'map(select(.key!="something"))'
关于您报告的错误,您漏掉了括号。应该是:
jq 'walk(if(type == "object" and (.key | test("something"))) then del(.) else . end)'
^ ^
正如@hek2mgl 所解释的,关于错误消息的问题的答案是 (X and Y | Z)
被解析为 (X and Y) | Z
。
您查询的主要问题是出现了 del(.)
。这 ”。”在这种情况下指的是对象,因此在这里使用 del/1 是完全错误的。由于不清楚您到底要做什么,让我大胆猜测它是删除对象 (.) 本身。这可以使用 empty
:
来完成
walk(if type == "object" and (.key | test("something"))
then empty
else . end)
更稳健:
walk(if type == "object" and (.key | (type == "string" and test("something")))
then empty
else . end)
考虑以下 jq 配置:
walk
(
if (type == "object" and .key | test("something")) then
del(.)
else
.
end
)
以及以下 JSON:
[
{
"key": "something",
"value": "something"
},
{
"key": "another thing",
"value": "another thing"
},
{
"key": "something",
"value": "something"
}
]
但是,jq 抛出以下错误:
jq: error (at :13): boolean (false) cannot be matched, as it is not a string
13 是输入的最后一行。它试图匹配什么布尔值?
这里一般不需要walk()
。我会像这样使用 map()
:
jq 'map(select(.key!="something"))'
关于您报告的错误,您漏掉了括号。应该是:
jq 'walk(if(type == "object" and (.key | test("something"))) then del(.) else . end)'
^ ^
正如@hek2mgl 所解释的,关于错误消息的问题的答案是
(X and Y | Z)
被解析为(X and Y) | Z
。您查询的主要问题是出现了
del(.)
。这 ”。”在这种情况下指的是对象,因此在这里使用 del/1 是完全错误的。由于不清楚您到底要做什么,让我大胆猜测它是删除对象 (.) 本身。这可以使用empty
: 来完成
walk(if type == "object" and (.key | test("something"))
then empty
else . end)
更稳健:
walk(if type == "object" and (.key | (type == "string" and test("something")))
then empty
else . end)