0

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

2 Answers 2

2

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 )

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.