Update array element of a JSON array with jq

40 views Asked by At

I have a JSON object and would like to update for example the array element "role[test09]" to "role[hello]", I don't have the index number. I have tried a few things but somehow can't figure it out.

How can I do this with jq ?

This is my JSON object.

    {
      "run_list": [
        "role[test01]",
        "role[test09]",
        "role[test05]"
      ]
    }

The updated object should look like this

    {
      "run_list": [
        "role[test01]",
        "role[hello]",
        "role[test05]"
      ]
    }
1

There are 1 answers

0
pmf On BEST ANSWER

A simple replacement with both, the old and the new values provided explicitly, would be to traverse to the desired item by iteration and selection, then using that as the LHS for an assignment:

jq '(.run_list[] | select(. == "role[test09]")) = "role[hello]"' input.json

Demo

Going further, you can import the string values using the --arg option. You could also have an elaborated update, like |= sub("test09"; "hello"). If you provide more details to the circumstances of your desired replacement, you could get responses more tailored to your specific needs.