bash将多个单词字符串解析为JSON值

时间:2016-03-11 18:23:20

标签: json bash github

用于从命令行创建新github repos的bash脚本可以正常工作,除非给出多字描述:

REPOSTRING={\"name\":\"$1\",\"description\":\"$2\",\"license_template\":\"mit\"}
echo $REPOSTRING
curl https://api.github.com/user/repos?access_token=xxx -d $REPOSTRING

调用脚本script testrepo testdescription按预期工作,但出现script testrepo "description with spaces"错误:

{
  "message": "Problems parsing JSON",
  "documentation_url": "https://developer.github.com/v3"
}
curl: (6) Could not resolve host: with
curl: (3) [globbing] unmatched close brace/bracket in column 33

即使脚本中的REPOSTRING显示为echo

,空格也会分散REPOSTRING
{"name":"testrepo","description":"description with spaces","license_template":"mit"}

空格出现在双引号内。

我需要对$2作业中的REPOSTRING做些什么特别的事情吗?我试过这个

REPOSTRING={\"name\":\"$1\",\"description\":\""$2"\",\"license_template\":\"mit\"}

但引用$2明确没有引起任何变化。

2 个答案:

答案 0 :(得分:2)

如果您希望保证JSON解析器可以接受输出,请使用知道如何生成JSON的工具 - 例如jq

repo_string=$(jq --arg name "$1" \
                 --arg description "$2" \
                 '.name=$name | .description=$description' \
                 <<<'{"license_template": "mit"}')

其他方法可能会遇到以下问题:

  • 文字"个字符(需要转义才能被视为数据而不是语法
  • 文字反斜杠(除非再次转义,否则将被JSON解析器视为语法而不是数据)。

答案 1 :(得分:-1)

你必须引用字符串赋值:

REPOSTRING="{\"name\":\"$1\",\"description\":\"$2\",\"license_template\":\"mit\"}"