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
}
]
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.
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.
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.
jq is an amazing little command line utility for working with JSON data.
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 }'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With