我正在尝试使用以下方法从Json文件中读取属性:
d['text']['entities']['mention'][0]['screen_name']
Json文件
{
"text" : {
"content" : "@narendramodi Did u even know the fare of metro has been increased by 65%",
"entities" : {
"user_mentions" : [ ],
"mention" : [
{
"indices" : [
0,
13
],
"id_str" : "18839785",
"screen_name" : "narendramodi",
"name" : "Narendra Modi",
"id" : 18839785
}
],
"hashtags" : [ ],
},
}
}
我正在尝试使用py2neo库在Neo4J数据库中加载许多json文件。
访问d['text']['entities']['mention'][0]['screen_name']
时
在其中"mention" : [ ],
提及字段为空的json文件之一中,它表示
IndexError:列表索引超出范围
错误非常明显,但我该如何处理呢?
答案 0 :(得分:0)
你可以使用try/except
阻止。像
try:
data = d['text']['entities']['mention'][0]['screen_name']
...
except IndexError:
data = None # or handle this case in other way
答案 1 :(得分:-1)
试试这个 -
mentions = d.get('text',{}).get('entities',{}).get('mention' ,[])
if len(mentions)>0:
print(mentions[0].get('screen_name',None))
else:
print(None)