0

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!

3 Answers 3

1

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"}]}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.