【问题标题】:jq if value match then update endjq 如果值匹配则更新结束
【发布时间】:2019-02-14 12:13:15
【问题描述】:

对于这个数据 https://jqplay.org/s/onlU9ghjn1

我无法找出正确的语法来做类似的事情

.gcp_price_list | ."CP-COMPUTEENGINE-OS" | 
(
    if ( .[].cores == "shared" ) then
        .[].cores = 0.5 
    end
)

似乎我需要else 部分,但我不知道该放什么。如果我这样做:

.gcp_price_list | ."CP-COMPUTEENGINE-OS" | 
(
    if ( .[].cores == "shared" ) then
        .[].cores = 0.5 
    else .[].cores = .[].cores end
)

结果中仍有“共享”,即

  "win": {
    "low": 0.02,
    "high": 0.04,
    "cores": "shared",
    "percore": true
  }

输入被复制到结果中,这不是我想要的。

相关,但我觉得它们不是很有帮助,问题

JQ If then Else

How do I update a single value in a json document using jq?


我的实际选择是用文本编辑器“全部替换”, 但如果有一个优雅的解决方案,我会在这里留下这个问题。

【问题讨论】:

    标签: json if-statement jq


    【解决方案1】:

    看起来你想要的:

    .gcp_price_list
    | ."CP-COMPUTEENGINE-OS"
    | map_values(
        if .cores == "shared" 
        then .cores = 0.5 
        else . end )
    

    在任何情况下,使用 .[].cores 等表达式作为 if、then 或 else 的参数时要小心,因为它们会产生结果流。

    今后,请遵循MCVE 准则。

    后记

    如果你想编辑 JSON 文档,你可以像这样使用|=:

    .gcp_price_list."CP-COMPUTEENGINE-OS" |= 
      map_values(
        if ( .cores == "shared" ) then
            .cores = 0.5 
        else . end
      )
    

    【讨论】:

      猜你喜欢
      • 2015-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-11
      • 2019-03-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多