Home > Software engineering >  How to add a new JSON object in an existing JSON file using jq and variable arguments
How to add a new JSON object in an existing JSON file using jq and variable arguments

Time:02-15

I have a json here which looks like:

{
  "cluster": "bvt-rtp-123",
  "state": "installed",
  "timestamp": "2022-02-14T10:23:01Z"
}

I want to use parameters/environment variables to dynamically add an object to that JSON object using jq The result should look like:

{
  "cluster": "bvt-rtp-123",
  "state": "installed",
  "timestamp": "2022-02-14T10:23:01Z",
  "aiops": {
    "catalog_source": "abc.com/123",
    "channel": "dev"
  }
}

wherein aiops, catalog_source and channel are parameterized by environment variables in this way:

parent_key=aiops
child_key=catalog_source
child_val=abc.com/123

I already tried this method, cat test.json | jq --arg parent "$parent_key" --arg child "$child_key" --arg child_val "$payload_val" '.[$key].[$child] = $child_val' But it throws this error:

jq: error: syntax error, unexpected '[', expecting FORMAT or QQSTRING_START (Unix shell quoting issues?) at <top-level>, line 1:
.[$key].[$child] = $child_val        
jq: 1 compile error

Please help!

CodePudding user response:

Define them using --arg, then set them using =. That way you can always add more subitems.

jq --arg parent_key aiops \
   --arg child_key catalog_source \
   --arg child_val abc.com/123 \
   '.[$parent_key]  = {($child_key): $child_val}' input.json
{
  "cluster": "bvt-rtp-123",
  "state": "installed",
  "timestamp": "2022-02-14T10:23:01Z",
  "aiops": {
    "catalog_source": "abc.com/123"
  }
}

Demo for the jq filter (simulating argument input with variable declaration)

  • Related