【问题标题】:Add new key to json array using jq使用 jq 向 json 数组添加新键
【发布时间】:2020-02-18 04:54:09
【问题描述】:

为什么“Append new keypair to JSON file with jq”中接受的答案在我的情况下不起作用?

我有一个文件newFile.json,其中包含:

[ { "groupId": 11, "lowerThreshold": 33, "target": { "alarm_id": 22 },
"thresholdPeriod": 3, "upperThreshold": 44 }, { "groupId": 31,
"lowerThreshold": 33, "target": { "alarm_id": 122 },
"thresholdPeriod": 3, "upperThreshold": 44 } ]

我想在 ruleGroup.json 中的数组中插入另一个值:

{ "groupId": "0", "target": { "alarm_id": "69" }, "upperThreshold":
"20", "lowerThreshold": "10", "thresholdPeriod": "5" }

根据接受的答案,我将ruleGroup.json 保存到obj

当我跑步时

jq --argjson obj '$obj' '. + [$obj]' < newFile.json

它返回:

[ "{\n \"groupId\": \"0\",\n \"target\": {\n \"alarm_id\": \"69\"\n
},\n \"upperThreshold\": \"20\",\n \"lowerThreshold\": \"10\",\n
\"thresholdPeriod\": \"5\"\n}" ]

这类似于$obj 值本身。它没有创建将这个值附加到数组的预期结果:

[ { "groupId": 11, "lowerThreshold": 33, "target": { "alarm_id": 22 },
"thresholdPeriod": 3, "upperThreshold": 44 }, { "groupId": 31,
"lowerThreshold": 33, "target": { "alarm_id": 122 },
"thresholdPeriod": 3, "upperThreshold": 44 }, { "groupId": "0",
"target": { "alarm_id": "69" }, "upperThreshold": "20",
"lowerThreshold": "10", "thresholdPeriod": "5" } ]

【问题讨论】:

标签: json bash jq


【解决方案1】:

如果您要添加的对象在文件中,您应该使用--slurpfile 而不是尝试将其读入shell 变量,然后将其传递给jq

$ jq --slurpfile obj ruleGroup.json '. + $obj' newFile.json 
[
  {
    "groupId": 11,
    "lowerThreshold": 33,
    "target": {
      "alarm_id": 22
    },
    "thresholdPeriod": 3,
    "upperThreshold": 44
  },
  {
    "groupId": 31,
    "lowerThreshold": 33,
    "target": {
      "alarm_id": 122
    },
    "thresholdPeriod": 3,
    "upperThreshold": 44
  },
  {
    "groupId": "0",
    "target": {
      "alarm_id": "69"
    },
    "upperThreshold": "20",
    "lowerThreshold": "10",
    "thresholdPeriod": "5"
  }
]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多