44

I want to use jq to put a stream of json objects into a json array, for example, from

{"a":1}
{"b":2}

to

[{"a":1},
{"b":2}]

But this would not work

echo '
{"a":1}
{"b":2}
'|jq '[.]'

since I got

[
  {
    "a": 1
  }
]
[
  {
    "b": 2
  }
]

1 Answer 1

50

Slurp it up with the -s option.

$ jq -s '.' <<< '{ "a": 1 } { "b": 2 }'
[
  {
    "a": 1
  },
  {
    "b": 2
  }
]

As another option, reading the values using inputs is a much more flexible alternative. You'll usually want to use this in conjunction with the -n option to prevent the first value from being consumed prematurely.

$ jq -n '[inputs]' <<< '{ "a": 1 } { "b": 2 }'
Sign up to request clarification or add additional context in comments.

11 Comments

I have a slight variation of this. My inputs are arrays [{"a":1}] and [{"b":2}] and the result should be without the inner arrays, ie. [{"a":1},{"b":2}]. Any tipp? It seems some concepts of jq are still eluding me.
@towi you could flatten the slurped inputs jq -s 'flatten'. Or better, iterate over each the inputs jq -n '[inputs[]]'
flatten was the hint I needed. But I first had to understand the concept, that jq no just reads one JSON entity but accepts a "stream" of them. With that I understood -s and with that I understood flatten. :-)
This does not answer the question as asked. What if I generate a streamwith jq and want to turn it into an array?
@reinierpost of course it does. what's not working for you?
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.