Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine the sequence of objects in jq into one object?

I would like to convert the stream of objects:

{   "a": "green",   "b": "white" } {   "a": "red",   "c": "purple" } 

into one object:

{   "a": "red",   "b": "white",   "c": "purple" } 

Also, how can I wrap the same sequence into an array?

[     {       "a": "green",       "b": "white"     },     {       "a": "red",       "c": "purple"     } ] 

Sadly, the manual is seriously lacking in comprehensiveness, and googling doesn't find the answers either.

like image 690
Jennifer M. Avatar asked Dec 27 '15 04:12

Jennifer M.


People also ask

How do I combine multiple objects into one?

To merge objects into a new one that has all properties of the merged objects, you have two options: Use a spread operator ( ... ) Use the Object. assign() method.

How do I combine arrays of objects into one?

Use the Array. We can use the JavaScript array reduce method to combine objects in an array into one object. We have the arr array which we want to combine into one object. To do that, we call reduce with a callback that returns an object with obj spread into the returned object. And we add the item.

What is jq slurp?

The slurp option ( -s ) changes the input to the jq program. It reads all the input values and build an array for the query input. Using with the raw input option ( -R ) means reading the entire input as a string. The inputs function is a special stream that emits the remaining JSON values given to the jq program.

What is jq filter?

A jq program is a "filter": it takes an input, and produces an output. There are a lot of builtin filters for extracting a particular field of an object, or converting a number to a string, or various other standard tasks.


1 Answers

If your input is a stream of objects, then unless your jq has inputs, the objects must be "slurped", e.g. using the -s command-line option, in order to combine them.

Thus one way to combine objects in the input stream is to use:

jq -s add 

For the second problem, creating an array:

jq -s . 

There are of course other alternatives, but these are simple and do not require the most recent version of jq. With jq 1.5 and later, you can use 'inputs', e.g. jq -n '[inputs]'

Efficient solution

For the first problem (reduction), rather than slurping (whether via the -s option, or using [inputs]), it would be more efficient to use reduce with inputs and the -n command-line option. For example, to combine the stream of objects into a single object:

jq -n 'reduce inputs as $in (null; . + $in)' 

Equivalently, without --null-input:

jq 'reduce inputs as $in (.; . + $in) 
like image 105
peak Avatar answered Sep 23 '22 05:09

peak