Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a JSON object stream into an array with jq

Tags:

json

jq

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
  }
]
like image 985
Qiang Li Avatar asked Apr 02 '15 03:04

Qiang Li


People also ask

How do I convert a JSON object to an array?

Approach 1: First convert the JSON string to the JavaScript object using JSON. Parse() method and then take out the values of the object and push them into the array using push() method.

Can we convert JSON to array?

Convert JSON to Array Using `json. The parse() function takes the argument of the JSON source and converts it to the JSON format, because most of the time when you fetch the data from the server the format of the response is the string. Make sure that it has a string value coming from a server or the local source.

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.

Can jq create JSON?

jq is an amazing little command line utility for working with JSON data.


1 Answers

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 }'
like image 180
Jeff Mercado Avatar answered Oct 08 '22 05:10

Jeff Mercado