Home > Net >  Transform a list of json value into an array
Transform a list of json value into an array

Time:01-06

Is there a way to transform / slurp a list of JSON values into an array ?

The idea is to replicate the functionality of -s / --slurp but for "internal" use.

When we iterate over the values of an array, we get a list of value. I would like to have a way to transform the list back into an array but without enclosing the expression with [ ], without using the array constructor.

I would like it to have the form of a filter. I already tried various things with reduce, foreach and bindings but it doesn't work

CodePudding user response:

No.

You're asking how to collect the outputs of a stream (list) using something of the form STREAM | .... Unfortunately, that's impossible.

When piping filter A into filter B as in A | B, and A happens to output a stream, then B is fed with each item of the stream separately, i.e. B runs as many times as there are items coming from A. Therefore no single execution of B will be able to see or collect all the (other) items of the stream.[1]

The code building the array must necessarily enclose STREAM.

  • [ STREAM ]
  • reduce STREAM as $_ ( []; . [$_] )
  • def array( s ): [ s ]; array( STREAM )
  • ARRAY | map( STREAM ) (An alternative to [ ARRAY | STREAM ].)
  • etc

For example,

jq --slurp .

can also be written as

jq --null-input '[ inputs ]'

But there's nothing equivalent that has the following form:

jq '...'

In short, you have an XY Problem.


  1. Courtesy of @pmf
  •  Tags:  
  • Related