有效的 GitHub api v4 查询不断返回错误“解析 JSON 的问题”

Bri*_*lip 6 curl github-api graphql github-graphql

以下是对 GitHub api v4 的 cURL 查询示例,该查询不断返回错误:

curl -H "Authorization: bearer token" -X POST -d " \
 { \
   \"query\": \"query { repositoryOwner(login: \"brianzelip\") { id } }\" \
 } \
" https:\/\/api.github.com\/graphql
Run Code Online (Sandbox Code Playgroud)

返回的错误:

{
  "message": "Problems parsing JSON",
  "documentation_url": "https://developer.github.com/v3"
}
Run Code Online (Sandbox Code Playgroud)

为什么我一直收到这个错误?


根据关于形成查询调用GH api v4 文档,上述 cURL 命令是有效的。以下是文档所说的支持我关于上述 cURL 命令有效的说法:

{
  "message": "Problems parsing JSON",
  "documentation_url": "https://developer.github.com/v3"
}
Run Code Online (Sandbox Code Playgroud)

注意:“query”的字符串值必须转义换行符,否则架构将无法正确解析它。对于 POST 正文,使用外部双引号和转义的内部双引号。

当我在GitHub GraphQL API Explorer 中输入上述查询时,我得到了预期的结果。对于 GH GraphQL Explorer,上述 cURL 命令的格式如下所示:

{
  repositoryOwner(login: "brianzelip") {
    id
  }
}
Run Code Online (Sandbox Code Playgroud)

Ber*_*tel 5

您必须在queryJSON 字段中转义嵌套的双引号,您的实际正文将是:

{
 "query": "query { repositoryOwner(login: \"brianzelip\") { id } }"
}
Run Code Online (Sandbox Code Playgroud)

所以替换\"brianzelip\"\\\"brianzelip\\\"

{
 "query": "query { repositoryOwner(login: \"brianzelip\") { id } }"
}
Run Code Online (Sandbox Code Playgroud)

您还可以使用单引号代替双引号来包裹正文:

curl -H "Authorization: bearer token" -d " \
 { \
   \"query\": \"query { repositoryOwner(login: \\\"brianzelip\\\") { id } }\" \
 } \
" https://api.github.com/graphql
Run Code Online (Sandbox Code Playgroud)

你也可以使用heredoc

curl -H "Authorization: bearer token" -d '
 {
   "query": "query { repositoryOwner(login: \"brianzelip\") { id } }"
 }
' https://api.github.com/graphql
Run Code Online (Sandbox Code Playgroud)