首页 > 解决方案 > 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)

标签: python-3.xapi

解决方案


您可以捕获在找不到特定键时引发的异常“ 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)

希望能帮助到你!


推荐阅读