Y.Y Y.Y - 1 year ago 101
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
in a loop,
I use the following code :

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

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

Answer Source

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


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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download