Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jq how to merge multiple arrays?

Tags:

json

jq

I have the following data, the output of multiple jq pipes:

 [
   {
     "Russia": 1073849
   }
 ]
 [
   {
     "Spain": 593730
   }
 ]
 [
   {
     "France": 387252
   }
 ]
 [
   {
     "UK": 371125
   }
 ]

My desired output is:

 [
   {
     "Russia": 1073849
   },
   {
     "Spain": 593730
   },
   {
     "France": 387252
   },
   {
     "UK": 371125
   }
 ]

Based on similar questions I tried '.[]|transpose|map(add)' and it gives an error: Cannot index object with number. Also I cannot group_by(key) because there is no common key in the objects.

like image 693
Neo Mosaid Avatar asked Oct 18 '25 05:10

Neo Mosaid


1 Answers

Assuming input.json file is:

[{"Russia": 1073849}]
[{"Spain": 593730}]
[{"France": 387252}]
[{ "UK": 371125}]

Then this:

jq -s 'reduce .[] as $x ([]; . + $x)' input.json

returns:

[
  {
    "Russia": 1073849
  },
  {
    "Spain": 593730
  },
  {
    "France": 387252
  },
  {
    "UK": 371125
  }
]

Notes:

  • jq can merge arrays with the + operator, e.g. [1]+[2] returns [1,2].
  • The -s flag reads input.json and put all entries into an array. So you end up with an array of arrays that you can merge with reduce.

This can be simplified even further with:

jq -s 'add' input.json
like image 101
customcommander Avatar answered Oct 20 '25 20:10

customcommander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!