【问题标题】:jq update json document to alter an array elementjq 更新 json 文档以更改数组元素
【发布时间】:2021-06-21 23:57:36
【问题描述】:

我知道这必须很简单,但由于某种原因,它使我无法找到给定条件的元素并修改其中一个字段。文档应在编辑后完全输出(sed 样式)。

{
  "state": "wait",
  "steps": { 
    "step1": [
      { "name":"Foo",    "state":"wait" },
      { "name":"Bar",    "state":"wait" }
    ],
    "step2": [
      { "name":"Foo",    "state":"wait" },
      { "name":"Zoinks", "state":"ready" }
    ],
    "step3": [
      { "name":"Foo",    "state":"cancel" }
    ]
  }
}

我希望这样的事情应该可行。

jq '. | (select(.steps[][].name=="Foo" and .steps[][].state=="wait") |= . + {.state:"Ready"}'

或

jq '. | (select(.steps[][]) | if (.name=="Foo" and .state=="wait") then (.state="Ready") else . end)

当然,期望的输出是

{
  "state": "wait",
  "steps": { 
    "step1": [
      { "name":"Foo",    "state":"ready" },
      { "name":"Bar",    "state":"wait" }
    ],
    "step2": [
      { "name":"Foo",    "state":"ready" },
      { "name":"Zoinks", "state":"ready" }
    ],
    "step3": [
      { "name":"Foo",    "state":"cancel" }
    ]
  }
}

相反,当我没有遇到神秘错误时,我要么修改文档中的顶级字段,要么修改 所有 元素的字段,或者多次重复整个文档。

非常感谢任何见解。

谢谢。

附言是否有比 [] 更好的语法来通配步骤下的命名元素?还是通过管道来识别select发现的索引?

【问题讨论】:

    标签: json select jq edit


    【解决方案1】:

    将.steps[][] 的输出传递到select 调用中,该调用选择具有所需name 和state 值的对象,然后在结果上设置state 值。

    $ jq '(.steps[][] | select(.name == "Foo" and .state == "wait")).state = "ready"' tmp.json
    {
      "state": "wait",
      "steps": {
        "step1": [
          {
            "name": "Foo",
            "state": "ready"
          },
          {
            "name": "Bar",
            "state": "wait"
          }
        ],
        "step2": [
          {
            "name": "Foo",
            "state": "ready"
          },
          {
            "name": "Zoinks",
            "state": "ready"
          }
        ],
        "step3": [
          {
            "name": "Foo",
            "state": "cancel"
          }
        ]
      }
    }
    

    您可以使用diff 帮助确认这一点(第一个jq 只是标准化了格式,因此只有第二个所做的更改才会显示在差异中):

    $ diff <(jq . tmp.json) <(jq '...' tmp.json)
    7c7
    <         "state": "wait"
    ---
    >         "state": "ready"
    17c17
    <         "state": "wait"
    ---
    >         "state": "ready"
    

    【讨论】:

    • 嗯,你用的是什么版本的jq?我有 jq-1.5-1-a5b5cbe ,对我来说,输出是 only 扁平化的步骤对象,没有它们的封闭结构,即 { "name": "Foo", "state": "ready" } {"name":"Bar", "state": wait" } ... 顶级属性,“steps”对象,“step1”数组,所有上下文都消失了。缺少逗号,输出甚至不是合法的 JSON 数组。有什么方法可以通过我需要进行的手术更改来发出完整的文档?谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-22
    • 1970-01-01
    • 2018-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多