matt525252 matt525252 - 1 month ago 19
JSON Question

json array into json stream with jq

This task is similar to this one but in my case I would like to go other way around.
So say we have input:

[
{
"name": "John",
"email": "john@company.com"
},
{
"name": "Brad",
"email": "brad@company.com"
}
]


and desired output is:

{
"name": "John",
"email": "john@company.com"
}
{
"name": "Brad",
"email": "brad@company.com"
}


I tried to write a bash function which will do it in loop:

#!/bin/bash

json=`cat $1`
length=`echo $json | jq '. | length'`

for (( i=0; i<$length ; i++ ))
do
echo $json | jq ".[$i]"
done


but it is obviously extremly slow...

Is there any way how to use
jq
better for this?

sat sat
Answer

You can use this :

jq '.[]' file

If you use the .[index] syntax, but omit the index entirely, it will return all of the elements of an array.

Test:

$ jq '.[]' file
{
  "email": "john@company.com",
  "name": "John"
}
{
  "email": "brad@company.com",
  "name": "Brad"
}