Home > OS >  How to concatenate sibling arrays using jq?
How to concatenate sibling arrays using jq?

Time:12-10

Given a JSON like:

[
  {
    "items": [1, 2, 3]
  },
  {
    "items": [3, 4]
  },
  {
    "items": [8, 9]
  }
]

how do you concatenate items with JQ into a single array like:

[
  1,
  2,
  3,
  3,
  4,
  8,
  9
]

A playground with this example: https://jqplay.org/s/r1RvAir27V

I need it to calc the length of all the arrays.

CodePudding user response:

Use flatten:

map(.items) | flatten

Demo


Or, map() the items instantly

map(.items[])

Demo


Or one of the many other options like:


All of those commands will produce:

[
  1,
  2,
  3,
  3,
  4,
  8,
  9
]

CodePudding user response:

One of many ways to construct the array in this particular class of cases would be:

[.[][][]]

This has the advantage of brevity and not using flatten, which should only be used with a full understanding of its semantics.

However, since the ultimate goal is to count the elements, it might be better to avoid constructing the array altogether, e.g. by using

def add(s): reduce s as $x (null; . $x);

Now you have another range of options, e.g.

add(..|objects|.items|length)
  • Related