GitHub解析JSON的GraphQL API问题
问题描述:
这里有什么问题?GitHub解析JSON的GraphQL API问题
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())
它如预期:)
为什么那么第二代码片段正常工作在我的例子作品? – Alex
更新了原始答案以包含解释。 –
@AdrianoMartins可以请看看这个问题[http://*.com/questions/42063825/how-to-access-the-github-graphql-api-from-java-without-running-curl-commands-插件] –