从Bash或Ruby创建有效的JSON字符串? [英] Create a valid JSON string from either Bash or Ruby?
本文介绍了从Bash或Ruby创建有效的JSON字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在 DigitalOcean 中创建20个小滴,并希望从Bash或Ruby.Bash起初似乎是最简单的,但是后来我发现JSON对于引号非常挑剔,并要求 -d
参数具有单引号.
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.
所以我下面的脚本不会扩展 $ line
变量=(
So my script below doesn't expand the $line
variable =(
问题
所以现在我在想,如果我使用Ruby完全有帮助吗?我会不会再遇到同样的问题,只是换一种语言?
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
推荐答案
使用 jq
之类的工具为您生成正确的JSON.
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"
这篇关于从Bash或Ruby创建有效的JSON字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文