2

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 2

2

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

.Objects += input.Objects

Online demo

0
2

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).

2
  • 1
    @oguzismail It probably works as you suggest but then you may come with another improvement like "do we really need to use reduce?" and this way, bit by bit, my solution morphs into your solution :-) I like your solution, it is the shortest and probably the fastest solution for the problem at hand, nothing to question about it. But this one is mine and I like it the way it is now. :-D
    – axiac
    Jan 20, 2021 at 16:47
  • 1
    @oguzismail I like the shorter version you gave for the very specific use case I have, involving 2 input objects, but you're right that this solution handles cases when there are more than 2, and your suggested modification works. I did try to figure out how to 'reduce' originally, couldn't quite get it right! Thank you both, very helpful.
    – Martin D
    Jan 20, 2021 at 17:56

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.