从获取请求 python 中检索 JSON 数据

Retrieve JSON data from get request python

我正在尝试接收 JSON 格式的数据,文档位于 - https://chargepoints.dft.gov.uk/api/help API.

然而当我运行这个

response = requests.get('http://chargepoints.dft.gov.uk/api/retrieve/registry/postcode/EC3A+7BR/limit/10/type/format/json/')
print(response)

它 returns <响应 [200]>。如何获得 JSON 格式的数据?

*EDIT 当我使用 response.json 我得到 <bound method Response.json of <Response [200]>> 当我使用 response.json() 我得到 JSONDecodeError("Expecting value", s, err.value)

您可以通过调用response.json()

获取响应数据

您可以通过 response.json 获取响应数据,或者您可以通过 response.text 获取原始文本 然后你可以使用json库轻松转换

import json
import requests

def get_json_from_url(url):
    content = get_url(url)
    js = json.loads(content)
    return js


def get_url(url):
    response = requests.get(url)
    content = response.content.decode('utf8')
    return content

url='https://chargepoints.dft.gov.uk/api/help'
json_content=get_json_from_url(url)

when I use response.json() I get JSONDecodeError("Expecting value", s, err.value)

这基本上意味着响应内容不是有效的json。

如何诊断此类问题?

在 Python 中,您可以检查未格式化的 response.content(属性,因此没有括号)并分析您看到的内容...但是因为它是一个简单的 GET,没有任何授权或任何东西,只需在您的浏览器中粘贴 url。

这就是你得到的:

<p:ChargeDevices xsi:schemaLocation="http://www.pod-point.com/cxns/NCR/1 National_Chargepoint_Registry.xsd ">
<Scheme>
<SchemeCode>NA</SchemeCode>
<SchemeData>
<OrganisationName>NA</OrganisationName>
<Website>NA</Website>
<TelephoneNo>NA</TelephoneNo>
</SchemeData>
...

这是 XML,而不是 JSON。你可能想知道为什么你没有得到 JSON,而你在 url...

中写了你的 /format/json/

查看 API documentation 并在浏览器中对其进行测试,我终于意识到您的 url 中的 /type/ 部分没有配对。您是从一个 json 示例中获得的,/type 是那里的端点名称。

删除 /type 部分即可:

response = requests.get('http://chargepoints.dft.gov.uk/api/retrieve/registry/postcode/EC3A+7BR/limit/10/format/json/')
print(response.json())

API 写得不好 - 使用 /option/value 格式使这个东西很难被发现(在 RESTful API 中,它应该是 option=value&option2=value2) ...仍然不是我见过的最糟糕的 api,但是它没有 return /type/format/json 部分的任何错误信息,这是一个非常糟糕的设计 - 或者它不知道“类型”选项或“json”“选项”没有提供任何值...