5axola
5axola

Reputation: 80

Modify keys in multiple nested objects/arrays

I want to modify the value of all x keys in a json that looks like:

{
  "a": {
    "b": {
      "c": [
        {
          "0": {
            "x": 23,
            "name": "AS"
          }
        },
        {
          "1": {
            "x": 23,
            "name": "AS"
          }
        },
        {
          "2": {
            "x": 23,
            "name": "Fe"
          }
        },
        {
          "3": {
            "x": 23,
            "name": "Pl"
          }
        }
      ]
    }
  }
}

I have tried multiple approaches, but I can't modify the value of x and obtain the full json as a result. All I managed to do is modify the value of x and obtain the last array as a result.

Here is the closest I have been to achieve the result: https://jqplay.org/s/Wx741btZOg

Upvotes: 0

Views: 720

Answers (2)

peak
peak

Reputation: 117027

Using |= one can simply perform the update by writing:

.a.b.c |= [.[]|.[].x=97]

or perhaps more clearly:

.a.b.c |= map(.[].x=97)

If you really do want to "modify the value of all x keys", then you could use walk:

walk(if type == "object" and has("x") then .x=97 else . end)

(If your jq does not have walk, then you can snarf its def from the web, e.g. from builtin.jq )

Upvotes: 2

oliv
oliv

Reputation: 13259

To change all x values to 97, you can try this jq command:

<file jq '.a.b.c as $in | .a.b.c=[ $in[] | .[].x=97 ]'

The command stores the parent of the object in the variable $in such that you can modify one of its sub element.

Upvotes: 1

Related Questions