1

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)

1 Answer 1

2

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

1 Comment

Instead of [ transpose[] | add] you can also use transpose | map(add) -- which I think is a little more readable.

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.