Home > other >  how to insert json var into another json array in bash
how to insert json var into another json array in bash

Time:08-02

Could you please assist me to on how I can merge two json variables in bash to get the desired output mentioned below {without manually lopping over .data[] array} ? I tired echo "${firstJsonoObj} ${SecondJsonoObj}" | jq -s add but it didn't parse through the array.

firstJsonoObj='{"data" :[{"id": "123"},{"id": "124"}]}'

SecondJsonoObj='{"etag" :" 234324"}'

desired output

{"data" :[{"id": "123", "etag" :" 234324"},{"id": "124", "etag" :" 234324"}]}

Thanks in advance!

CodePudding user response:

You can append to each data element using =:

#!/bin/bash

firstJsonoObj='{"data" :[{"id": "123"},{"id": "124"}]}'
SecondJsonoObj='{"etag" :" 234324"}'

jq -c ".data[]  = $SecondJsonoObj" <<< "$firstJsonoObj"

Output:

{"data":[{"id":"123","etag":" 234324"},{"id":"124","etag":" 234324"}]}

CodePudding user response:

Please don't use double quotes to inject data from shell into code. jq provides the --arg and --argjson options to do that safely:

#!/bin/bash

firstJsonoObj='{"data" :[{"id": "123"},{"id": "124"}]}'
SecondJsonoObj='{"etag" :" 234324"}'

jq --argjson x "$SecondJsonoObj" '.data[]  = $x' <<< "$firstJsonoObj"
# or
jq --argjson a "$firstJsonoObj" --argjson b "$SecondJsonoObj" -n '$a | .data[]  = $b'
{
  "data": [
    {
      "id": "123",
      "etag": " 234324"
    },
    {
      "id": "124",
      "etag": " 234324"
    }
  ]
}

CodePudding user response:

jq -s add will not work because you want to add the second document to a deeper level within the first. Use .data[] = input (without -s), with . acessing the first and ìnput accessing the second input:

echo "${firstJsonoObj} ${SecondJsonoObj}" | jq '.data[]  = input'

Or, as bash is tagged, use a Heredoc:

jq '.data[]  = input' <<< "${firstJsonoObj} ${SecondJsonoObj}"

Output:

{
  "data": [
    {
      "id": "123",
      "etag": " 234324"
    },
    {
      "id": "124",
      "etag": " 234324"
    }
  ]
}

Demo

  • Related