How to create for-loops with jq in bash

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

 {

    "results" : [

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

    ]
}

I want the output to have n files: 1.json, 2.json, n.json. Accordingly, 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 am not defined

+4
source share
3 answers

While the answers above are correct, note that interpolating shell variables in jq scripts is a terrible idea for everyone but the most trivial scenarios. In any of the suggested solutions, replace the following:

jq ".results[$i]"

With the following:

jq --arg i "$i" '.results[$i | tonumber]'
+2
source

Try

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

, .

IHTH

+2

Single quotes are probably what confuse you. Bash variables are not expanded in single quotes. You pass a literal string .results[$i]to jq. Use double quotes instead:

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

Source: https://habr.com/ru/post/1621360/


All Articles