问题
I would like to create 20 droplets in DigitalOcean, and would like to do it from either Bash or Ruby. Bash seemed at first to be the easiest, but then I turned out JSON is super picky about quotes and demands the -d
argument to have single quotes.
So my script below doesn't expand the $line
variable =(
Question
So now I am thinking, would it at all help if I used Ruby? Wouldn't I end up in the same problem again, just in another language?
token=123
while read line; do
curl -qq -X POST -H "Content-Type: application/json" -H "Authorization: Bearer $token" -d '{"name":"02267-$line","region":"fra1","size":"s-2vcpu-4gb","image":"ubuntu-18-04-x64","ssh_keys":["14063864","22056139","23743266"],"backups":false,"ipv6":false,"user_data":null,"private_networking":null,"volumes": null,"tags":["02267-$line"]}' "https://api.digitalocean.com/v2/droplets"
done < list.txt
list.txt
tokyo
seoul
osaka
kobe
回答1:
Use a tool like jq
to generate correct JSON for you.
# Note: $x here is *not* a shell variable, but a jq variable
# that jq will expand, ensuring the value is correctly quoted.
filter='{name: "02267-\($x)",
region: "fra1",
size: "s-2vcpu-4gb",
image: "ubuntu-18-04-x64",
ssh_keys ["14063864","22056139","23743266"],
backups: false,
ipv6: false,
user_data: null,
private_networking: null,
volumes: null,
tags: ["02267-\($x)"]
}'
jq -n --argjson x "$line" "$filter" |
curl -qq -X POST \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $token" \
-d @- \
"https://api.digitalocean.com/v2/droplets"
来源:https://stackoverflow.com/questions/54023812/create-a-valid-json-string-from-either-bash-or-ruby