Last active
January 11, 2017 09:23
-
-
Save ralph-tice/12f949ec9df397b01da698030f179135 to your computer and use it in GitHub Desktop.
updating a json array via jq
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ "arr" : [ | |
{ "id": 3, "bar": "x", "fum": 3.14 }, | |
{ "id": 77, "bar": "y", "fum": 0 }, | |
{ "id": 9, "bar": "z", "fum": -1 } | |
] | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"arr": [ | |
{ | |
"id": 3, | |
"bar": "q", | |
"fum": 3.14 | |
}, | |
{ | |
"id": 77, | |
"bar": "w", | |
"fum": 0, | |
"foo": "555" | |
}, | |
{ | |
"id": 9, | |
"bar": "z", | |
"fum": -1 | |
} | |
] | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
77, w, 555 | |
3, q |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment