带有json.loads的json KeyError [英] json KeyError with json.loads

查看:490
本文介绍了带有json.loads的json KeyError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JSON似乎困扰着以下语句:

JSON seems to be hiccuping on the following statements:

{"delete":{"status":{"id":12600579001,"user_id":55389449}}}

代码段:

temp = json.loads(line)
text = temp['text']

当上面的代码片段遇到与上面的JSON'dictionary'类似的行时,我得到以下错误输出:

I get the following error output when the above code snippet encounters lines similar to the above JSON 'dictionary':

text = temp['text']
KeyError: 'text'

是因为行中没有文本"键,还是因为字典中没有删除"键?

Is it because there is no "text" key in the line or because "delete" is not in the dictionary?

推荐答案

是因为行中没有文本"键,还是因为字典中没有删除"键?

Is it because there is no "text" key in the line or because "delete" is not in the dictionary?

这是因为没有文本"键.如果您print temp或检查键'text'是否在生成的Python词典中,您会注意到没有名为'text'的键.实际上,temp只有一个键:'delete'. 'delete'引用的字典包含一个键'status',该键包含另一个包含两个键的字典:'user_id''id'.

It's because there is no "text" key. If you print temp or check whether the key 'text' is in the resulting Python dictionary, you'll notice that there is no key named 'text'. In fact, temp only has one key: 'delete'. The dictionary that is referenced by 'delete' contains a single key 'status' that contains another dictionary with two keys: 'user_id' and 'id'.

换句话说,您的结构是这样的:

In other words, your structure is this:

{
    "delete" : {
        "status" : {
            "id" : 12600579001,
            "user_id" : 55389449
        }
    }
}

如您所见,在任何地方都没有文本"键.

As you can see, there is no "text" key anywhere.

此外,您可以自己检查:

Furthermore, you can check it yourself:

>>> 'text' in temp
False
>>> 'delete' in temp
True

这篇关于带有json.loads的json KeyError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆