带有json.loads的json KeyError

use*_*775 10 python json

JSON似乎在以下声明中打嗝:

{"delete":{"status":{"id":12600579001,"user_id":55389449}}}
Run Code Online (Sandbox Code Playgroud)

代码段:

temp = json.loads(line)
text = temp['text']
Run Code Online (Sandbox Code Playgroud)

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

text = temp['text']
KeyError: 'text'
Run Code Online (Sandbox Code Playgroud)

是因为行中没有"text"键,还是因为"delete"不在字典中?

tör*_*kus 8

使用dict.get(key[, default])如果在缺少键时存在有效的情况: temp.get('text')而不是temp['text'] 不会抛出异常,但None如果找不到键则返回空值。

EAFP(比许可更容易请求宽恕)比 LBYL(Look Before You Leap)更 Pythonic。

  • 这解决了我的问题。请注意,在某些情况下,返回 Null(Python 中的“None”)将成为进一步处理的问题,因此如果键丢失,您可以使用 temp.get('text', 'X') 更改该值应该是什么其中 X 是一个字符串 (3认同)

Chr*_*ron 7

似乎发生这种情况是因为其中没有“文本”。也许您可以使用类似

'text' in temp
Run Code Online (Sandbox Code Playgroud)

在尝试使用“文本”之前先进行检查。

编辑:

我采用了注释中给出的示例,并在其中添加了一个if / elif / else块。

#! /usr/bin/python
import sys
import json
f = open(sys.argv[1])
for line in f:
    j = json.loads(line)
    try:
        if 'text' in j:
            print 'TEXT: ', j['text']
        elif 'delete' in j:
            print 'DELETE: ', j['delete']
        else:
            print 'Everything: ', j
    except: 
        print "EXCEPTION: ", j
Run Code Online (Sandbox Code Playgroud)

样本块1:

{u'favorited':错误,u'contributors':无,u'truncated':False,u'text':----摘录----}

样本块2:

{u'delete':{u'status':{u'user_id':55389449,u'id':12600579001L}}}


Dus*_*tin 7

是因为行中没有"text"键,还是因为"delete"不在字典中?

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

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

{
    "delete" : {
        "status" : {
            "id" : 12600579001,
            "user_id" : 55389449
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

此外,您可以自己检查:

>>> 'text' in temp
False
>>> 'delete' in temp
True
Run Code Online (Sandbox Code Playgroud)


Sam*_*amB 1

为什么不把它放在第一行和第二行之间:

print temp
Run Code Online (Sandbox Code Playgroud)