Python 遇到 KeyError:如何在数据不在 JSON 中时跳过错误?

0 投票
2 回答
51 浏览
提问于 2025-04-14 18:33

有一个人遇到了一个简单的Python脚本问题,这个脚本是用来调用一个API(应用程序接口),然后把获取到的信息显示在一个简单的文本框里。问题在于,有时候这个API会提供所有的信息,有时候则不会。当API提供了所有信息时,脚本运行得很顺利,能把所有信息都显示出来;但有时候,API缺少某个特定的部分,这就会导致一个叫做KeyError的错误。

如果API没有这个部分,就需要完全跳过这个区域,或者更好的是,显示一段文字,比如“没有信息”,如果API有这个部分,就正常显示出来。

下面是这个脚本:


  data = {'name': 'Kev', 'connected': 'ONLINE', 'time': '2024-03-03T23:01:00Z', 'up-loader': [{'uploaded': 'Yes', 'upload-time': '2024-03-03T18:01:00Z'}]}

    # Main Info - allways in the json
  InfoNAME = data["name"]
  InfoCONN = data["connected"]
  InfoTIME = data["time"]
    # This info is only in the json sometimes - here is where the problem is
  InfoUPLOAD = data['up-loader'][0]["uploaded"]
  InfoUPTIME = data['up-loader'][0]["upload-time"] 

# Take info from above and load it onto the chart below
    # deletes all the text that is currently in the TextBox 
  text_box.delete('1.0', END)   
    # insert new data into the TextBox
# Name
  text_box.insert(END, "Name:  ")
  text_box.insert(END, InfoNAME)
# Online status  
  text_box.insert(END, "Status: ")
  text_box.insert(END, InfoCONN)
# Last online Time  
  text_box.insert(END, "Last Online: ")
  text_box.insert(END, InfoTIME)
# Upload logger
  text_box.insert(END, "Was there an upload:")  
  text_box.insert(END, InfoUPLOAD)
# Upload time
  text_box.insert(END, "When was the upload: ")
  text_box.insert(END, InfoUPTIME)

期待你的回复。

2 个回答

0
if somekey in mydata: 

这个代码运行得非常好,这让我不仅能解决错误,还可以自定义在什么地方显示什么文本,真是太棒了。代码如下:

我还在某些地方用了 .get('name', '没有记录名字'),但最有效的方式是 if somekey in mydata:

data = {'name': 'Kev', 
        'connected': 'ONLINE', 
        'time': '2024-03-03T23:01:00Z',
        'up-loader': [{'uploaded': 'Yes', 
                       'upload-time': '2024-03-03T18:01:00Z'}]}

# Main Info - always in the json
InfoNAME = data.get('name', 'No Name Recorded')
InfoCONN = data["connected"]
InfoTIME = data["time"]

# CODE THAT FIXED ISSUE BELOW
if 'up-loader' in data:
    InfoUPLOAD = data['up-loader'][0]["uploaded"]
    InfoUPTIME = data['up-loader'][0]["upload-time"]

# Take info from above and load it onto the chart below  
# deletes all the text that is currently in the TextBox
text_box.delete('1.0', END)

# Insert new data into the TextBox
# Name
text_box.insert(END, "Name:  ")
text_box.insert(END, InfoNAME)
# Online status
text_box.insert(END, "Status: ")
text_box.insert(END, InfoCONN)
# Last online Time
text_box.insert(END, "Last Online: ")
text_box.insert(END, InfoTIME)

# Upload logger
if 'up-loader' in data:
    text_box.insert(END, "Was there an upload:")
    text_box.insert(END, InfoUPLOAD)
    text_box.insert(END, "When was the upload: ")
    text_box.insert(END, InfoUPTIME)
0

你有两个选择。

你可以用 in 这个关键词来专门检查某个键是否存在:

if somekey in mydata:
    # yes it is present, so it is safe to
    # access mydata['somekey']

或者你可以使用 .get() 函数,这样你可以提供一个默认值,如果找不到这个键,就会用这个默认值:

value = mydata.get(somekey, 'Oops this was not found')

撰写回答