phil
phil

Reputation: 174

JQ - Select JSON subarray by value then update by index

I'm trying to process some JSON output and modify a value but struggling to get anywhere.

I have no control over the source data, which looks like this:

[
    [
        "dave",
        "likes",
        "rabbits"
    ],
    [
        "brian",
        "likes",
        "fish"
    ]
]

In pseudo code, I need to:

I've managed to use map and select to get the subarray I want (jq -r -c 'map(select(.[]=="brian"))), but not build that into anything more useful...

Help much appreciated!

Upvotes: 1

Views: 191

Answers (1)

Inian
Inian

Reputation: 85653

Update the required value by specifying the array indices and using the |= update select construct

map(select(.[0] == "brian")[2] |= "cats" )

This also populates [2] with "cats" even if previously there was no value at the specific index.

Of course it goes without saying, the indices could be dynamically arrived at as well

map(select(any(.[]; . == "brian"))[2] |= "cats")

Upvotes: 2

Related Questions