Preeti
Preeti

Reputation: 753

How to update the value of the item in an array if it exists in json using jq?

I have a Json file which I want to update using jq. I am working on Ubuntu with jq-1.6

test_data.json
{
    "A": "12",
    "B": "34",
    "C": [
        ["X", "test1"],
        ["Y", "test2"],
        ["Z", "test3"]
    ]
}

Now I want to update array C with new key:value pair. But, if the any of the key already exists then it's value should be updated.

update='[
    ["Z", "test4"],
    ["D", "test5"],
    ["E", "test6"]
    ]'

In this case the item Z already exists in test_data.json but update has new value for the item.

Expected output:

{
    "A": "12",
    "B": "34",
    "C": [
        ["X", "test1"],
        ["Y", "test2"],
        ["Z", "test4"],
        ["D", "test5"],
        ["E", "test6"]
    ]
}

So far, I could do

cat test_data.json | jq --argjson val "${update}" '.C += $val')

But this is not updating value for item Z, instead adding new entry.

Can anyone please let me know how to resolve this?

Thanks in advance.

Upvotes: 0

Views: 187

Answers (1)

pmf
pmf

Reputation: 36601

The .C array and the $update array both have arrays as items. You need to consider their first item to be a unique key, so that clashes can lead to overwrites. One way could be turning them into an INDEX object first, then add up those, and retrieve their items back into an array:

jq --argjson val "$update" '.C |= [[., $val | INDEX(.[0])] | add[]]' test_data.json
{
  "A": "12",
  "B": "34",
  "C": [
    [
      "X",
      "test1"
    ],
    [
      "Y",
      "test2"
    ],
    [
      "Z",
      "test4"
    ],
    [
      "D",
      "test5"
    ],
    [
      "E",
      "test6"
    ]
  ]
}

Upvotes: 1

Related Questions