尝试将数组元素添加到可能存在的配置文件中

Trying to add array element to a maybe existing config file

我正在测试以下内容:

#!/usr/bin/env bash

element="$(jo -p \
    locations=["$(jo \
        name="$name" \
        address="$address" \
        latitude=$lat \
        longitude=$long \
        gridId=$grid_id \
        gridX=$grid_X \
        gridY=$grid_Y \
        countyUGC="$countyUGC" \
        zoneUGC="$zoneUGC" \
        stationId="$stationId")"])"

if [[ -e weather.locations ]]; then
    jq --argjson element "$element" '. += $element' \
        weather.locations >weather.locations.temp && mv weather.locations.temp weather.locations
else
    echo "$entry" >weather.locations
fi

我第一次 运行 这个,文件将不存在(我的 [[ ]] 的原因)。但是后来,它似乎总是修改初始元素而不是添加。我的目标:使用新元素附加位置数组(我认为不需要更新,但“名称”将是要关闭的字段)

jo 的输出:(当然所有字段都会填写)

{
  "locations": [
    {
      "name": "home",
      "address": "123 Main St, MyTown MyState",
      "latitude": null,
      "longitude": null,
      "gridId": null,
      "gridX": null,
      "gridY": null,
      "countyUGC": null,
      "zoneUGC": null,
      "stationId": null
    }
  ]
}

感谢指点

您的 jo 命令生成一个带有“位置”字段的对象,其值将用于替换现有对象之一(. 指的是外围对象而不是它的“位置”数组)。

相反,您需要以下内容:

jq --argjson element "$element" '.locations += $element.locations'