Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.