theapache64
theapache64

Reputation: 11734

Append JSON Objects using jq

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 ?

Upvotes: 9

Views: 11224

Answers (2)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

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"
  }
}

Upvotes: 16

oliv
oliv

Reputation: 13239

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

Upvotes: 5

Related Questions