【问题标题】:Json parsing in shell script在shell脚本中解析Json
【发布时间】:2019-08-29 14:28:14
【问题描述】:

我正在尝试自动创建 github 存储库。以下是我的代码:

pushtogithub() {
        git init
        git config user.name "user name"
        git config user.email "user email"
        git add .
        git commit -m "Initial commit"
        content=$(curl -s -u githubusername:githubaccesstoken https://api.github.com/user/repos -d '{"name":"$1", "private":true}')
        repo=$(jq -r '.ssh_url' <<< "${content}" )
        echo $repo created
        git remote add origin git@github.com:githubusername/$repo.git
        git push -u origin master
}

我的 github 存储库总是使用 -1 名称创建。

我在这里做错了什么?

【问题讨论】:

  • 在 curl 的请求数据中,$1 用单引号括起来,不会被展开。例如,您可以将该部分更改为-d "{\"name\":\"$1\", \"private\":true}"
  • 这解决了使用-1 名称创建repo。但我仍然没有在repo 中得到正确的值。我将文字值 echo jq -r... 放入其中。
  • echo 应该从jq 子shell 中删除,我假设您已经将它放在那里调试您的命令,但在发布之前忘记将其删除。
  • 如果您要使用 jq,请正确使用它——不仅要解析 JSON,还要创建 JSON。跨度>
  • @Gulshan,...如果在不使用语法感知编码器的情况下将内容插入 JSON 中“有效”,那么您就没有使用足够有趣的数据进行测试。 :)

标签: shell curl jq github-api


【解决方案1】:

替换:

curl ... -d '{"name":"$1", "private":true}'

...与:

curl ... -d "$(jq -n --arg name "$1" '{"name": $name, "private": true}')"

也就是说:您使用jq解析 JSON 的方式没有任何问题;问题是您尝试使用jq创建 JSON


顺便说一句,尝试解决此问题的简单但错误的方法是更改​​引用类型:

#### DO NOT DO THIS
curl ... -d '{"name": "'"$1"'", "private": true}'

...或...

### DO NOT DO THIS EITHER
curl ... -d "{\"name\":\"$1\", \"private\":true}"

在第一个示例中,除了$1 之外的所有内容都用单引号括起来;但然后在展开之前结束那些单引号,切换到双引号上下文,在那里展开 $1,然后切换回来。

在第二个示例中,我们只是将整个内容放在双引号中,转义那些打算作为文字而不是句法的内容。

然而,这两种方法都是错误的;试着看看当你的名字是 Foo "The Leet" Bar 时它做了什么——文字引号与 JSON 引号混淆,使生成的 JSON 无效,除非你使用知道如何转义它们的工具(如 jq)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-29
    相关资源
    最近更新 更多