python-3.x - KeyError:“纬度”
问题描述
我目前正在尝试使用 API 来获取 Buffalo 中的数据并从 JSON URL 中返回数据,并将其放置为以下格式:经度、纬度和 Viodesc。
但是,我相信我在迭代时遇到了困难,因为某些值没有纬度和经度,因此给了我一个KeyError
.'latitude'
我不确定这是否是我的代码中的错误以及如何更改它
import json
from urllib import request
def get_ticket_data(string):
answer = []
urlData = string
webURL = request.urlopen(urlData)
data = webURL.read()
ans = json.loads(data.decode())
for x in ans:
arr = []
arr.append(x["lattitude"])
arr.append(x["longtitude"])
arr.append(x["viodesc"])
return answer.append(ans)
解决方案
您可以捕获在找不到特定键时引发的异常“ KeyError ”。处理异常,以便即使缺少密钥,您也可以在不停止代码的情况下继续下一条记录。
代码片段:
import json
from urllib import request
def get_ticket_data(string):
answer = []
urlData = string
webURL = request.urlopen(urlData)
data = webURL.read()
ans = json.loads(data.decode())
for x in ans:
try:
arr = []
arr.append(x["lattit**strong text**ude"])
arr.append(x["longtitude"])
arr.append(x["viodesc"])
except KeyError:
continue
return answer.append(ans)
希望能帮助到你!
推荐阅读
- angular - 组件自身更改时如何避免表达式“检查后更改”错误
- javascript - 循环中的 document.getElementById 返回 null
- c# - C# MVC detect if XMLHttpRequest
- php - 致命错误:未捕获错误:函数名称必须是 php/class-style-generator.php 中的字符串
- jquery - 在ajax ASP.NET MVC中将数据从视图传递到控制器
- android - 使用 wix/detox 与不是由您的应用生成的 UI 进行交互
- swift - 暂停代码,直到在 Swift 中获得 UIAlertController 的响应
- oracle - 调用主页的 ID 值时返回空值 [OWCS] v11.8
- vue.js - Cors 在一条路线上,但在另一条路线上没有 Vue
- database - 码头集装箱可以(应该)多大?