'Trying to add array element to a maybe existing config file

I'm testing the following:

#!/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

The 1st time I run this, the file will not exist (reason for my [[ ]]). But subsequent times, it seems to always modify the initial element instead of adding. My goal: Append location array with new element (I don't see any need for updating, but "name" would be the field to key off of)

output of the jo: (of course all the fields would be filled in)

{
  "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
    }
  ]
}

Thanks for any pointers

jq


Solution 1:[1]

Your jo command produces an object with a "locations" field, whose value will be used to replace the one of the existing object (. refers to the outlying object rather than to its "locations" array).

Instead you'll want the following :

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Aaron