jq update json document to alter an array element

qpgpyjmq  于 5个月前  发布在  其他
关注(0)|答案(2)|浏览(61)

我知道这很简单,但是由于某种原因,我不知道如何找到一个给定条件的元素并修改它的一个字段。

{
  "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" }
    ]
  }
}


相反,当我没有得到隐含错误时,我要么修改文档中的顶级字段,要么修改 * 所有 * 元素的字段,要么多次重复整个文档。
任何见解不胜感激。
谢谢.
p.s.有没有比[]更好的语法来通配符步骤下面的命名元素?或者在管道后面来标识select所发现的索引?

pgccezyw

pgccezyw1#

.steps[][]的输出导入select调用,该调用选择具有所需namestate值的对象,然后在结果上设置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只是规范化格式,因此只有第二个jq所做的更改才会显示在diff中):

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

mbskvtky

mbskvtky2#

对于一个复杂的文档,

keya: AAA
keyb: BBB
keyc:
  arrayc:
  - name: item1
    someparam1: i1p1
    someparam2: i1p2
  - name: item2
    someparam1: i2p1
    someparam2: i2p2

个字符
导致

keya: AAA
keyb: BBB
keyc:
  arrayc:
    - name: item1
      someparam1: i1p1
      someparam2: i1p2
    - name: item2
      someparam1: i2p1
      someparam2: modified

相关问题