Skip to content

Instantly share code, notes, and snippets.

@ralph-tice
Last active January 11, 2017 09:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ralph-tice/12f949ec9df397b01da698030f179135 to your computer and use it in GitHub Desktop.
Save ralph-tice/12f949ec9df397b01da698030f179135 to your computer and use it in GitHub Desktop.
updating a json array via jq
{ "arr" : [
{ "id": 3, "bar": "x", "fum": 3.14 },
{ "id": 77, "bar": "y", "fum": 0 },
{ "id": 9, "bar": "z", "fum": -1 }
]
}
{
"arr": [
{
"id": 3,
"bar": "q",
"fum": 3.14
},
{
"id": 77,
"bar": "w",
"fum": 0,
"foo": "555"
},
{
"id": 9,
"bar": "z",
"fum": -1
}
]
}
#!/bin/bash
cp input.json tmp.json
while read -r LINE;
do
IFS=", " read -ra ADDR <<< $LINE
jq --arg id ${ADDR[0]} --arg bar "${ADDR[1]}" --arg foo "${ADDR[2]}" \
'.arr | map(if .id == ($id | tonumber) then .bar = $bar else . end) | if $foo != "" then map(if .id == ($id | tonumber) then .foo = $foo else . end) else . end | {"arr": .}' tmp.json > tmp2.json
mv tmp2.json tmp.json
done <updates
mv tmp.json output.json
77, w, 555
3, q
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment