NiveditaK
NiveditaK

Reputation: 51

how to insert json var into another json array in bash

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!

Upvotes: 0

Views: 495

Answers (3)

pmf
pmf

Reputation: 36078

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

Upvotes: 0

pmf
pmf

Reputation: 36078

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

Upvotes: 1

Ted Lyngmo
Ted Lyngmo

Reputation: 117298

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

Upvotes: 1

Related Questions