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.

5
  • 1
    You single-quoted the argument to -d, so none of your parameters get expanded. Commented Feb 22, 2022 at 16:13
  • 2
    Use jq to generate the payload, as it takes care of safely escaping any parameter values to generate valid JSON for you. Commented Feb 22, 2022 at 16:13
  • there is also a missing } at the end of your "json" object. Commented Feb 22, 2022 at 16:14
  • you may want to give jo a try. Commented Feb 22, 2022 at 16:16
  • The highly-ranked answers on the linked duplicate are going to give you a more robust solution than the answer that's currently directly added here; I strongly recommend linking through and reading them. Commented Feb 22, 2022 at 20:48

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.