如何解决如何从 json 响应中输出特定数据?
我对在 python 中使用 API 还很陌生,我正在尝试创建一个系统来输出以前赛车比赛的数据。我已经向 API 发送了请求,但我很难让它只输出一个特定的数据(例如时间、位置)。当我打印发送的原始 JSON 数据时,我得到了这个。
function hideOnLoad() {
$("#ThePages").hide();
$("#TheRunTime").hide();
$("#Borrowable").hide();
$("#BorrowedBy").hide();
$("#TheDate").hide();
}
$(document).ready(function () {
hideOnLoad();
$("#Types select").change(function () {
var value = $(this).val();
if (value == "Book") {
$("#ThePages").show();
$("#TheRunTime").hide().removeAttr();
$("#Borrowable").show();
$("#BorrowedBy").show();
$("#TheDate").show();
}
else if (value == "AudioBook") {
$("#ThePages").hide().removeAttr();
$("#TheRunTime").show();
$("#Borrowable").show();
$("#BorrowedBy").show();
$("#TheDate").show();
}
else if (value == "ReferenceBook") {
$("#ThePages").show();
$("#TheRunTime").hide().removeAttr();
$("#Borrowable").hide().removeAttr();
$("#BorrowedBy").hide().removeAttr();
$("#TheDate").hide().removeAttr();
}
else if (value == "DVD") {
$("#ThePages").hide().removeAttr();
$("#TheRunTime").show();
$("#Borrowable").show();
$("#BorrowedBy").show();
$("#TheDate").show();
}
else {
hideOnLoad();
}
});
});
为了掌握 API,我只是尝试输出特定种族的简单数据,一旦我能做到这一点,我就能够将其放大并输出各种数据。我以为它就像输入 {
"MRData": {
"RaceTable": {
"Races": [
{
"Circuit": {
"Location": {
"country": "Spain","lat": "41.57","locality": "Montmeló","long": "2.26111"
},"circuitId": "catalunya","circuitName": "Circuit de Barcelona-Catalunya","url": "http://en.wikipedia.org/wiki/Circuit_de_Barcelona-Catalunya"
},"date": "2020-08-16","raceName": "Spanish Grand Prix","round": "6","season": "2020","time": "13:10:00Z","url": "https://en.wikipedia.org/wiki/2020_Spanish_Grand_Prix"
}
],"season": "2020"
},"limit": "30","offset": "0","series": "f1","total": "1","url": "http://ergast.com/api/f1/2020/6.json","xmlns": "http://ergast.com/mrd/1.4"
}
}
一样简单(如下所示),但我收到一条错误消息:
键错误:'时间'
我的源代码:
print(data['time'])
感谢任何帮助!
解决方法
像这样...
import json
data = """{
"MRData":{
"xmlns":"http://ergast.com/mrd/1.4","series":"f1","url":"http://ergast.com/api/f1/2020/6.json","limit":"30","offset":"0","total":"1","RaceTable":{
"season":"2020","round":"6","Races":[
{
"season":"2020","url":"https://en.wikipedia.org/wiki/2020_Spanish_Grand_Prix","raceName":"Spanish Grand Prix","Circuit":{
"circuitId":"catalunya","url":"http://en.wikipedia.org/wiki/Circuit_de_Barcelona-Catalunya","circuitName":"Circuit de Barcelona-Catalunya","Location":{
"lat":"41.57","long":"2.26111","locality":"Montmeló","country":"Spain"
}
},"date":"2020-08-16","time":"13:10:00Z"
}
]
}
}
}"""
jsonData = json.loads(data)
种族是一个数组,在这种情况下只有一个种族,因此您可以将其指定为 ["Races"][0]
print(jsonData["MRData"]["RaceTable"]["Races"][0]["time"])
,
data['time']
如果你有一个扁平的字典,但你有一个嵌套的字典/列表结构,那么:
data["MRData"]["RaceTable"]["Races"][0]["time"]
data["MRData"]
返回另一个字典,它有一个键 "RaceTable"
。这个键的值又是一个字典,它有一个键 "Races"
。这个值是一个种族列表,其中你只有一个。种族再次是具有键 time
的字典。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。