Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQ checking for values in an array given as a parameter

I've got a simple JQ filter to update some values in an array based on the "Key", for example this is my input:

[
    {
        "Key": "IDontCare",
        "Value": "something"
    },
    {
        "Key": "Tag1",
        "Value": "123-456"
    },
    {
        "Key": "Tag2",
        "Value": "121-717"
    }
]

I want to update both tags to a new value (same value for both), so I've got this command, that works:

jq --arg NEW_VALUE '987-654' \
    '[.[] |= if(.Key=="Tag1" or .Key=="Tag2") then (.Value=$NEW_VALUE) else . end]'

However I want to update different tags in different runs and would like to pass them as another argument. But not sure how to change the if() to look up the tags from the parameter.

I tried something like this but that's apparently not the right way:

jq --argjson TAGS '["Tag1","Tag2"]' --arg NEW_VALUE '987-654' \
    '[.[] |= if(.Key|in($TAGS)) then (.Value=$NEW_VALUE) else . end]'

Any ideas?

like image 382
MLu Avatar asked Sep 30 '26 03:09

MLu


1 Answers

You can use IN to see if the value is part of the list and use a much simpler update assignment using select as

jq --arg NEW_VALUE '987-654' --argjson TAGS '["Tag1","Tag2"]' '
   map(select( .Key | IN($TAGS[] ) ).Value |= $NEW_VALUE )' json
like image 122
Inian Avatar answered Oct 01 '26 19:10

Inian