Y.Y Y.Y - 1 month ago 5
Bash Question

how can i use variable in jq?(MacOS,shell)

I got a Json string as:

{
"id": 3397,
"title": "title_1"
}
{
"id": 3396,
"title": "title_2"
}


what I want to do is get every
id
in a loop,
I use the following code :

for (( i = 0; i < requestCount; i++ )); do
requestId=$(echo $jsonString[$i] | jq '.id')
echo requestId;
done


but it doesn't work, I think the way I use variable is wrong, I can't find anything useful here jq.

Answer

Let jq do the iterating. (That is, let jq do the iterating through the input stream of JSON objects.) For example:

$ jq .id <<< "$json" | while read id ; do echo "hello $id"; done

Output:

hello 3397
hello 3396

This way, you don't have to know how many JSON objects are in the input. You might want to use "read -r", or "IFS= read -r".

The alternatives are ugly and inefficient, e.g.:

$ for ((i=0;i<2;i++)) ; do jq -s --argjson i "$i" '.[$i].id' <<< "$json" ; done
Comments