Home > front end >  JQ - Select JSON subarray by value then update by index
JQ - Select JSON subarray by value then update by index

Time:06-22

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:

  • Select the subarray with value "brian" at index 0
  • Change the value at index [2] in the selected array to "cats"
  • Return the complete modified array

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!

CodePudding user response:

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")
  • Related