簡體   English   中英

使用 jq 向 json 數組添加新鍵

[英]Add new key to json array using jq

為什么“ 使用 jq 將新密鑰對附加到 JSON 文件”中接受的答案在我的情況下不起作用?

我有一個文件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" } ]

如果要添加的對象在文件中,則應該使用--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"
  }
]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM