Using JQ to merge two JSON snippets from one file

Viewed 60

I've got output from a script that outputs two structurally identical JSON snippets into one file:

{
    "Objects": [
        {
            "Key": "somevalue",
            "VersionId": "someversion"
        }
    ],
    "Quiet": false
}
{
    "Objects": [
        {
            "Key": "someothervalue",
            "VersionId": "someotherversion"
        }
    ],
    "Quiet": false
}

I would like to pass this output through JQ to have one Objects[] list, concatenating all of the objects within the two lists, and outputting the same overall structure. I can accomplish it with piping between two separate JQ commands:

jq '.Objects[]' inputfile | jq -s '{"Objects":., "Quiet":false}' -

But I'm wondering if there is a more elegant way to do so using only one invocation of JQ.

I'm currently using JQ version 1.5 but can update if needed.

2 Answers

You don't need to invoke JQ twice there. The second object can be fetched using the input keyword.

.Objects += input.Objects

Online demo

You can use reduce:

jq -s 'reduce .[] as $item ({ Quiet: false }; .Objects += $item.Objects)'

See it in action.

As @oguz-ismail suggested in a comment, the -s (slurp) flag can be removed by using inputs to get the rest of the entries after the first one:

jq 'reduce inputs as $item (.; .Objects += $item.Objects)'

See it in action.

Both versions work with any number of entries in the input (the second version requires at least one).

Related