使用json时Python获取KeyError

2024-08-31 10:38:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python程序中使用json

temp = json.loads(text2)
data = temp["data"]
try:
    ld = data["all"]
    globals()['currentbrowserall'] = ld
    del data["all"]
except:
    s = str(sys.exc_info()[0])
    s2 = str(sys.exc_info()[1])
    s3 = str(sys.exc_info()[2])
    print "%s, %s, %s" % (s, s2, s3)

问题是我总是异常.KeyError在“所有”上,而每次键在那里,数据以及一切都像它应该的那样工作,但它输出错误。为什么?有什么不对劲吗?在

下面是一个json示例

^{pr2}$

Tags: 程序infojsondatas3sysalltemp
1条回答
网友
1楼 · 发布于 2024-08-31 10:38:36

我确信您的datadict没有名为all的属性:

  1. 在使用delprint data)之前打印dict进行检查。在
  2. 使用以下方法确保您不会得到例外情况:-在

    如果data.has_密钥(“全部”): 删除数据['all']

相关问题 更多 >