GitHub GraphQL API 解析问题 JSON

GitHub GraphQL API Problems parsing JSON

这里有什么问题?

query='{ repositoryOwner(login : "ALEXSSS") { login repositories (first : 30){ edges { node { name } } } } }'

headers = {'Authorization': 'token xxx'}

r2=requests.post('https://api.github.com/graphql', '{"query": \"'+query+'\"}',headers=headers)

print (r2.json())

我有

{'message': 'Problems parsing JSON', 'documentation_url': 'https://developer.github.com/v3'}

但下面这段代码可以正常工作

query1= '''{ viewer { login name } }'''  

headers = {'Authorization': 'token xxx'} 

r2=requests.post('https://api.github.com/graphql', '{"query": \"'+query1+'\"}',headers=headers) 

print (r2.json())

我试过更改引号(从 " 到 ' 或 " 等等),但它不起作用。

问题与双引号 (") 有关。 在第一个片段中,当您将 '{"query": \"'+query+'\"}' 与查询变量连接时,您会得到以下结果:

{"query": "{ repositoryOwner(login : "ALEXSSS") { login repositories (first : 30){ edges { node { name } } } } }"}

注意来自 "ALEXSSS" 的双引号是如何不转义的,因此结果字符串不是 json 有效格式。

当您 运行 第二个片段时,结果字符串为:

{"query": "{ viewer { login name } }"}

这是一个有效的 json 字符串。

最简单和最好的解决方案是简单地使用 JSON 库而不是尝试手动执行,这样您就不必担心转义字符。

import json

query='{ repositoryOwner(login : "ALEXSSS") { login repositories (first : 30){ edges { node { name } } } } }'
headers = {'Authorization': 'token xxx'}

r2=requests.post('https://api.github.com/graphql', json.dumps({"query": query}), headers=headers)

print (r2.json())

但请记住,您也可以手动转义查询中的字符:

query='{ repositoryOwner(login : \"ALEXSSS\") { login repositories (first : 30){ edges { node { name } } } } }'
headers = {'Authorization': 'token xxx'}

r2=requests.post('https://api.github.com/graphql', '{"query": "'+query1+'"}', headers=headers)

print (r2.json())

它按预期工作:)