jq json根据条件从内部数组中检索值,并将其添加到数组之外

时间:2018-03-22 22:33:46

标签: arrays maps jq flatten

我的输入

{
"data": {
    "assets": [{
        "aDASD": "1056bda9-2598-4fdf-bd99-db3924464a75",
        "KEY": "a7e2ef79-41aa-4a36-9ca1-1f388917eb12.ahnl",
        "key2": "store-order-picking-units-api",
        "key3": "1.0.1",
        "tags": [{
                "value": "abcd",
                "key": null,
                "mutable": false
            },
            {
                "value": "rest",
                "key": null,
                "mutable": false
            },
            {
                "value": "123",
                "key": null,
                "mutable": false
            }, {
                "value": "system",
                "key": null,
                "mutable": true
            },
            {
                "value": "market",
                "key": null,
                "mutable": true
            }
        ],
        "type": "mytype"
    }]
}

}

我想输出如下

{
"data": {
    "assets": [{
        "aDASD": "1056bda9-2598-4fdf-bd99-db3924464a75",
        "KEY": "a7e2ef79-41aa-4a36-9ca1-1f388917eb12.ahnl",
        "key2": "store-order-picking-units-api",
        "key3": "1.0.1",
        "tags": [{
                "value": "abcd",
                "key": null,
                "mutable": false
            },
            {
                "value": "rest",
                "key": null,
                "mutable": false
            },
            {
                "value": "123",
                "key": null,
                "mutable": false
            }, {
                "value": "system",
                "key": null,
                "mutable": true
            },
            {
                "value": "market",
                "key": null,
                "mutable": true
            }
        ],
        "type": "mytype",
        "newkey1": "system",
        "newkey2": "market"
    }]
}

}

响应包含newkey1和newkey2。现在这里是棘手的部分。填充newkey1时,值可以是" system" "处理"对于newkey2,值可以是" market"," finance"等。

换句话说,如果.data.assets[].tags[].values中的任何一个是系统或进程等,则应填充newkey1 ...类似newkey2仅限于市场,财务等。

使用jq是否复杂或首先可以实现?请帮忙。

1 个答案:

答案 0 :(得分:1)

jq是Turing-complete,所以你很幸运: - )

您的要求并不完全清楚,但以下内容会产生您期望的输出,并且可以帮助您:

.data.assets |= map(
    .newkey1 = if any(.tags[].value; . == "system") then "system" else null end
  | .newkey2 = if any(.tags[].value; . == "market") then "market" else null end 
)

这里的关键点是:

  • |=可用于更新;
  • any(stream; condition)检查流中任何项的条件是否为真