Добавить новый ключ в массив json, используя jq - PullRequest
0 голосов
/ 18 февраля 2020

Почему принятый ответ в " Добавить новую пару ключей к JSON файлу с 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" } ]

1 Ответ

1 голос
/ 18 февраля 2020

Если объект, который вы хотите добавить, находится в файле, вы должны использовать --slurpfile вместо того, чтобы пытаться прочитать его в переменную оболочки, а затем передать его в 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"
  }
]
...