【问题标题】:jq ignores else clausejq 忽略 else 子句
【发布时间】:2021-07-03 14:53:31
【问题描述】:

我想使用 jq 搜索和替换基于行的 json 数据中的特定值,如果匹配为 false,则保持对象不变。

考虑以下input.json

{"foo":{"bar":"one"}}
{"foo":{"bar":"two"}}

我尝试了以下语句,但是 else 子句被忽略了,因此不匹配的行会丢失:

jq -c '. | if (select(.foo.bar == "one")) then .foo.bar |= "ok" else . end' input.json

产生结果:

{"foo":{"bar":"ok"}}

以下命令产生正确的输出:

jq -c '(. | select(.foo.bar == "one")).foo.bar = "ok"' input.json

想要的输出:

{"foo":{"bar":"ok"}}
{"foo":{"bar":"two"}}

为什么第一条命令在else子句中输出对象.失败?

【问题讨论】:

标签: json if-statement select jq


【解决方案1】:

不要使用select:

. | if .foo.bar == "one" then .foo.bar |= "ok" else . end

select 对过滤很有用,但如果没有选择,它不会返回 false 值,它不会返回任何东西。

【讨论】:

  • 换句话说,if empty then 1 else 2 end 产生空流。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-31
  • 1970-01-01
相关资源
最近更新 更多