Skip to content

Instantly share code, notes, and snippets.

@thomasdarimont
Created April 26, 2019 20:28
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 thomasdarimont/c56c3cf87633d7595819cd22fdc2f8a3 to your computer and use it in GitHub Desktop.
Save thomasdarimont/c56c3cf87633d7595819cd22fdc2f8a3 to your computer and use it in GitHub Desktop.
JQ Filter & Update Objects
json=$(cat << EOF
{
    "id":"test1234",
    "components": [
        {
            "id":"c1",
            "type":"foo",
            "bubu":1,
            "secret":"****"
        },
        {
            "id":"c2",
            "type":"foo",
            "bubu":2,
            "secret":"****"
        },
        {
            "id":"c3",
            "type":"bar",
            "secret":"****"
        }
    ]
}
EOF
)
echo $json | jq -c '.. | objects | select(.id == "c3")'

Output

{"id":"c3","type":"bar","secret":"c3-secret"}
echo $json | jq -c '.. | objects | select(.type == "foo" and .bubu == 2)'
{"id":"c2","type":"foo","bubu":2,"secret":"c2-secret"}
echo $json | jq -r -c '(..|objects|select(.id == "c1")).secret |= "c1-secret"'
{"id":"test1234","components":[{"id":"c1","type":"foo","bubu":1,"secret":"c1-secret"},{"id":"c2","type":"foo","bubu":2,"secret":"****"},{"id":"c3","type":"bar","secret":"****"}]}
echo $json | jq -r -c '(..|objects|select(.id == "c1")).secret |= "c1-secret" | (..|objects|select(.id == "c2")).secret |= "c2-secret"'
{"id":"test1234","components":[{"id":"c1","type":"foo","bubu":1,"secret":"c1-secret"},{"id":"c2","type":"foo","bubu":2,"secret":"c2-secret"},{"id":"c3","type":"bar","secret":"****"}]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment