【问题标题】:GitHub GraphQL API Problems parsing JSONGitHub GraphQL API 解析 JSON 的问题
【发布时间】:2017-04-06 05:05:00
【问题描述】:

这里有什么问题?

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())

我已尝试更改引号(从 " 变为 ' 或与 " 等等),但它不起作用。

【问题讨论】:

    标签: python python-requests github-api graphql


    【解决方案1】:

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

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

    注意"ALEXSSS" 中的双引号是如何没有转义的,因此生成的字符串不是 json 有效格式。

    当你运行第二个 sn-p 时,结果字符串是:

    {"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())
    

    它按预期工作:)

    【讨论】:

    猜你喜欢
    • 2018-07-19
    • 2019-01-30
    • 1970-01-01
    • 2020-01-18
    • 2020-09-08
    • 1970-01-01
    • 2018-01-15
    • 1970-01-01
    • 2021-11-22
    相关资源
    最近更新 更多