我正在查询C3.aiAPI,用于分析统一的新冠肺炎数据。我看到,默认情况下,所有API都返回xml格式的字符串。目前,我正在使用python库xmltodict将格式转换为json。有什么方法可以直接请求JSON响应吗?
下面是我正在运行的代码:
import json, requests, xmltodict
url = "https://api.c3.ai/covid/api/1/outbreaklocation/fetch/"
request_data = {
"spec": {
"include": "id",
"limit": 1
}
}
response = requests.post(url=url, json=request_data)
print(response.text)我得到的相应答复如下:
<fetchResponse version="2.0">
<type>
<module>metadata</module>
<name>FetchResult</name>
<bindings>
<k>T</k>
<v>
<type>
<module>typesys</module>
<name>ReferenceType</name>
</type>
<name>OutbreakLocation</name>
<mixing>true</mixing>
</v>
</bindings>
</type>
<objs>
<k>0</k>
<v>
<id>AaenHunze_Drenthe_Netherlands</id>
<meta>
<fetchInclude>[id,version,typeIdent]</fetchInclude>
<fetchType>OutbreakLocation</fetchType>
</meta>
<version>262145</version>
<typeIdent>EP_LOC</typeIdent>
</v>
</objs>
<count>1</count>
<hasMore>true</hasMore>
</fetchResponse>我使用以下代码将xml转换为json:
fetch_object = xmltodict.parse(response.text)发布于 2020-04-13 17:58:24
您可以尝试的一件事是在请求中指定一个Content标头。
import json, requests, xmltodict
url = "https://api.c3.ai/covid/api/1/outbreaklocation/fetch/"
headers={'content-type': 'application/json'}
request_data = {
"spec": {
"include": "id",
"limit": 1
}
}
response = requests.post(url=url, json=request_data, headers=headers)
print(response.text)发布于 2020-04-17 00:16:55
发布于 2020-04-19 16:34:33
默认情况下,服务器返回XML。要获得JSON响应,必须将接受请求header设置为application/json。如果您发送一个请求,其中的内容类型标头被设置为application/json,但没有指定接受值,则仍然会从API获得XML响应。
根据约翰霍普金斯大学()的数据,这里有一个cURL样本,要求对2020年3月意大利确诊死亡人数进行评估。它可以从任何shell界面进行测试,也可以导入到Postman应用程序中,例如:
curl 'https://api.c3.ai/covid/api/1/outbreaklocation/evalmetrics' \
--request POST \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--data-binary '{
"spec": {
"ids": ["Italy"],
"expressions":["JHU_ConfirmedDeaths"],
"interval":"DAY",
"start":"2020-03-01",
"end":"2020-03-31"
}
}'这将返回一个JSON对象。下面是与上一次调用相同的调用,但不包括Accept标头。在这种情况下,返回一个XML响应:
curl 'https://api.c3.ai/covid/api/1/outbreaklocation/evalmetrics' \
--request POST \
--header 'Content-Type: application/json' \
--data-binary '{
"spec": {
"ids": ["Italy"],
"expressions":["JHU_ConfirmedDeaths"],
"interval":"DAY",
"start":"2020-03-01",
"end":"2020-03-31"
}
}'https://stackoverflow.com/questions/61182225
复制相似问题