Home > Enterprise >  How to merge two JSON array variables?
How to merge two JSON array variables?

Time:05-12

Most of the googling shows it with files but I want to do it with variables. Tried a few things with the documentation but I can't find the right filter or function or not sure If my approach even makes sense.

var1='[
{"a":"1","b":"2","c":"3"},
{"a":"4","b":"5","c":"6"},
{"a":"7","b":"8","c":"9"}
]'

var2='[
{"d":"x","e":"y"},
{"d":"z","e":"q"},
{"d":"w","e":"v"}
]'

The result I want is

'[
{"a":"1","b":"2","c":"3","d":"x","e":"y"},
{"a":"4","b":"5","c":"6","d":"z","e":"q"},
{"a":"7","b":"8","c":"9","d":"w","e":"v"}
]'

If i use

jq -n --argjson var1 "$var1" --argjson var2 "$var2" '$var1   $var2'

it just makes a bigger array with all 6 objects, not 3 longer ones

If I use * or |= it gives errors

I'm not even sure if it's a filter I need or a builtin function (map doesn't seem to be doing this)

CodePudding user response:

Use transpose to align the elements from both input arrays, then add to combine both sides:

jq -n --argjson var1 "$var1" --argjson var2 "$var2" '
  [$var1, $var2] | [transpose[] | add]
'
[
  {
    "a": "1",
    "b": "2",
    "c": "3",
    "d": "x",
    "e": "y"
  },
  {
    "a": "4",
    "b": "5",
    "c": "6",
    "d": "z",
    "e": "q"
  },
  {
    "a": "7",
    "b": "8",
    "c": "9",
    "d": "w",
    "e": "v"
  }
]
  • Related