我这里有个json,看上去:
{
"cluster": "bvt-rtp-123",
"state": "installed",
"timestamp": "2022-02-14T10:23:01Z"
}我想使用参数/环境变量来使用jq动态地向那个JSON对象添加一个对象,结果应该如下所示:
{
"cluster": "bvt-rtp-123",
"state": "installed",
"timestamp": "2022-02-14T10:23:01Z",
"aiops": {
"catalog_source": "abc.com/123",
"channel": "dev"
}
}其中,aiops、catalog_source和channel以这种方式被环境变量参数化:
parent_key=aiops
child_key=catalog_source
child_val=abc.com/123我已经尝试过这个方法,cat test.json | jq --arg parent "$parent_key" --arg child "$child_key" --arg child_val "$payload_val" '.[$key].[$child] = $child_val',但是它抛出了这个错误:
jq: error: syntax error, unexpected '[', expecting FORMAT or QQSTRING_START (Unix shell quoting issues?) at <top-level>, line 1:
.[$key].[$child] = $child_val
jq: 1 compile error发布于 2022-02-14 12:41:00
使用--arg定义它们,然后使用+=设置它们。这样,您就可以始终添加更多的子项。
jq --arg parent_key aiops \
--arg child_key catalog_source \
--arg child_val abc.com/123 \
'.[$parent_key] += {($child_key): $child_val}' input.json{
"cluster": "bvt-rtp-123",
"state": "installed",
"timestamp": "2022-02-14T10:23:01Z",
"aiops": {
"catalog_source": "abc.com/123"
}
}jq过滤器的演示 (用变量声明模拟参数输入)
https://stackoverflow.com/questions/71112010
复制相似问题