Jq:在步行过程中测试一个领域



考虑以下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:错误(在:13(:布尔值(假(无法匹配,因为它不是字符串

13 是输入的最后一行。它试图匹配什么布尔值?

  1. 正如@hek2mgl所解释的,您关于错误消息的问题的答案是 (X and Y | Z) 被解析为 (X and Y) | Z .

  2. 查询的主要问题是发生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)
通常这里

不需要walk()。我会使用这样的map()

jq 'map(select(.key!="something"))'

关于您报告的错误,您错过了括号。它应该是:

jq 'walk(if(type == "object" and (.key | test("something"))) then del(.) else . end)'
                                 ^                        ^

最新更新