0

I'm trying to do a post using curl in the following loop:

for name in "${first_name[@]}"; do
        password=$(</dev/urandom tr -dc '12345!@#$%qwertQWERTasdfgASDFGzxcvbZXCVB' | head -c16; echo "")
        curl -X POST -H "Content-Type: application/json" -H "Authorization: Token ${token}" -d '{"username": "${username[$name]}", "password": "${password}", "email": "${email[$name]}",  "first_name": "${name}", "last_name": "${last_name[$name]}", "is_staff": "${staff[$name]}", "is_active": "${active[$name]}", "groups": ["${group_id}"]' https://app.com/api/users/users/
done

With this syntax I am getting the following error:

{"detail":"JSON parse error - Expecting ',' delimiter: line 1 column 242 (char 241)"}

Each of the variables have a value as I was printing them inside the loop with an echo.

It looks like a syntax error. Any ideas what it is wrong?

Thank you.

Albert
  • 191
  • 1
  • 3
  • 23

1 Answers1

0

Try this :

for name in "${first_name[@]}"; do
    password=$(</dev/urandom tr -dc '12345!@#$%qwertQWERTasdfgASDFGzxcvbZXCVB' |
               head -c16; echo "")
    curl -X POST \
        -H "Content-Type: application/json" \
        -H "Authorization: Token ${token}" \
        -d "$(cat << EOF
{"username": "${username[$name]}",
 "password": "${password}",
 "email": "${email[$name]}",
 "first_name": "${name}",
 "last_name": "${last_name[$name]}",
 "is_staff": "${staff[$name]}",
 "is_active": "${active[$name]}",
 "groups": ["${group_id}"]
}
EOF
        )" https://app.com/api/users/users/
done
Philippe
  • 20,025
  • 2
  • 23
  • 32
  • This doesn't fix any data that isn't valid inside a JSON string without escaping. Consider a user who goes by `Joe ("Johnny") Hill` -- the `"`s need backslashes added. A tool like `jq` will do that automatically. – Charles Duffy Feb 22 '22 at 20:46