简体   繁体   中英

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 ?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM