How to create for-loops with jq in bash

crocefisso picture crocefisso · Dec 23, 2015 · Viewed 10.8k times · Source

I'm trying to split a json file into various json files. The input (r1.json) looks like :

 {

    "results" : [

                {
            content 1
}
,
{
            content 2
}
,
{
            content n
}

    ]
}

I'd like the output to be n files : 1.json, 2.json, n.json. Respectively containing {content 1}, {content 2} and {content n}.

I tried :

for i in {0..24}; do cat r1.json | jq '.results[$i]' >> $i.json; done

But I have the following error: error: i is not defined

Answer

shellter picture shellter · Dec 23, 2015

Try

for i in {0..24}; do cat r1.json | jq ".results[$i]" >> $i.json; done

Note that shell variables can't be expanded inside of single-quotes.

IHTH