2

I have two arrays with the same amount of elements but with different keys/values. I want to integrate the key/value of the second array into the first for each index/position.

1.json

[ { "name": "xxx", "url": "yyy", "thumbnail": "nnn" }, { "name": "bla bla", "url": "some-url", "thumbnail": "another-pic" } ] 

2.json

[ { "spotifyUrl": "first-spotify-url" }, { "spotifyUrl": "second-spotify-url" } ] 

The result I would like to achieve:

[ { "name": "xxx", "url": "yyy", "thumbnail": "nnn", "spotifyUrl": "first-spotify-url" }, { "name": "bla bla", "url": "some-url", "thumbnail": "another-pic", "spotifyUrl": "second-spotify-url" } ] 

I already tried different things but couldn't find the result I wanted. For example this one here:

jq -n ' (input | map_values([.])) as $one | input as $two | reduce ($two|keys_unsorted[]) as $k2 ( $one; .[$k2] += [$two[$k2]] ) ' 1.json 2.json 

is almost what I want, except that the spotify-url is nested into its own object and looks like this:

[ { "name": "xxx", "url": "yyy", "thumbnail": "nnn" }, { "spotifyUrl": "first-spotify-url" } ] 

I appreciate any help and bet it's a lot simpler than I can think of. Thanks in advance.

1
  • 1
    Its a pretty good effort! but transpose is the key ingredient here Commented Sep 28, 2022 at 12:14

1 Answer 1

6

It's easier than that.

jq -s 'transpose | map(add)' 1.json 2.json 

Online demo

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot, works like a charm. I already tried it with map, but the transpose in combination obviously did the trick.
Wow. I have been trying to find a quick way to do this with two output vars, yet everywhere I've looekd it's either convoluted, no longer works, or really annoying use cases that don't quite just squish like objects together. Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.