10

I've below JSON structure

{

    "a": "aVal",
    "x": {
      "x1": "x1Val",
      "x2": "x2Val"
    }
    "y": {
      "y1": "y1Val"
    }
}

I want to add "x3": "x3Val","x4": "x4Val" to x. So the output should be

{
    ...
    "x": {
      ....
      "x3": "x3Val",
      "x4": "x4Val",
    }
    ...
}

Is it possible using jq ?

2 Answers 2

16

Of course, it's pretty simple for jq:

jq '.x += {"x3": "x3Val","x4": "x4Val"}' file.json

The output:

{
  "a": "aVal",
  "x": {
    "x1": "x1Val",
    "x2": "x2Val",
    "x3": "x3Val",
    "x4": "x4Val"
  },
  "y": {
    "y1": "y1Val"
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Simple and perfect (y)
5

Yes it is, provided you add a comma on line 8 after the closing bracket } (otherwise jq won't parse your input JSON data):

$ jq '.x.x3="x3val"|.x.x4="x4val"' file
{
  "a": "aVal",
  "x": {
    "x1": "x1Val",
    "x2": "x2Val",
    "x3": "x3val",
    "x4": "x4val"
  },
  "y": {
    "y1": "y1Val"
  }
}

Alternatively if you need to pass values as argument, use the option --arg:

jq --arg v3 "x3val" --arg v4 "x4val" '.x.x3=$v3|.x.x4=$v4' file

1 Comment

Thank you for the response.

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.