Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass bash variable to JSON

I'm trying to write a sample script where I'm generating names like 'student-101...student-160'. I need to post JSON data and when I do, I get a JSON parse error.

Here's my script:

name="student-10"

for i in {1..1}
do
    r_name=$name$i
    echo $r_name
    curl -i -H 'Authorization: token <token>' -d '{"name": $r_name, "private": true}' "<URL>" >> create_repos_1.txt
    echo created $r_name
done

I always get a "Problems parsing JSON" error. I've tried various combination of quotes, etc but nothing seems to work!

What am I doing wrong?

like image 867
Saturnian Avatar asked Oct 14 '25 23:10

Saturnian


2 Answers

First, your name property is a string, so you need to add double quotes to it in your json.

Second, using single quotes, bash won't do variable expansion: it won't replace $r_name with the variable content (see Expansion of variable inside single quotes in a command in bash shell script for more information).

In summary, use:

-d '{"name": "'"$r_name"'", "private": true}'
like image 89
Derlin Avatar answered Oct 17 '25 14:10

Derlin


Another option is to use printf to create the data string:

printf -v data '{"name": "%s", "private": true}' "$r_name"
curl -i -H 'Authorization: token <token>' -d "$data" "$url" >> create_repos_1.txt
like image 32
glenn jackman Avatar answered Oct 17 '25 12:10

glenn jackman