GitHub GraphQL API解析JSON的问题

Ale*_*lex 8 python github-api python-requests graphql

这有什么不对?

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())
Run Code Online (Sandbox Code Playgroud)

我有

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

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

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

headers = {'Authorization': 'token xxx} 

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

print (r2.json())
Run Code Online (Sandbox Code Playgroud)

我试着改变字符串("on"或"with"等等),但它不起作用.

Adr*_*ins 11

该问题与双引号(")有关.在第一个代码片段中,当您'{"query": \"'+query+'\"}'使用查询变量加入时,您将得到以下结果:

{"query": "{ repositoryOwner(login : "ALEXSSS") { login repositories (first : 30){ edges { node { name } } } } }"}
Run Code Online (Sandbox Code Playgroud)

请注意双引号如何"ALEXSSS"不被转义,因此结果字符串不是json有效格式.

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

{"query": "{ viewer { login name } }"}
Run Code Online (Sandbox Code Playgroud)

这是一个有效的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())
Run Code Online (Sandbox Code Playgroud)

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

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())
Run Code Online (Sandbox Code Playgroud)

它按预期工作:)