Create a valid JSON string from either Bash or Ruby?

一个人想着一个人 提交于 2021-01-29 08:46:46

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!