如何使用 jq 和可变参数在现有 JSON 文件中添加新的 JSON 对象

How to add a new JSON object in an existing JSON file using jq and variable arguments

我这里有一个 json 看起来像:

{
  "cluster": "bvt-rtp-123",
  "state": "installed",
  "timestamp": "2022-02-14T10:23:01Z"
}

我想使用 parameters/environment 变量动态添加一个对象到 JSON 使用 jq 的对象 结果应如下所示:

{
  "cluster": "bvt-rtp-123",
  "state": "installed",
  "timestamp": "2022-02-14T10:23:01Z",
  "aiops": {
    "catalog_source": "abc.com/123",
    "channel": "dev"
  }
}

其中aiopscatalog_sourcechannel是这样通过环境变量参数化的:

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

请帮忙!

使用 --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"
  }
}

Demo 用于 jq 过滤器(使用变量声明模拟参数输入)