从 Json 文件读取值
Reading values from Json file
我正在尝试使用以下命令从 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']
在其中一个 json 文件中 "mention" : [ ],
提及字段为空,它说
IndexError: 列表索引超出范围
错误很明显,但我该如何处理?
试试这个 -
mentions = d.get('text',{}).get('entities',{}).get('mention' ,[])
if len(mentions)>0:
print(mentions[0].get('screen_name',None))
else:
print(None)
您可以只使用 try/except
块。喜欢
try:
data = d['text']['entities']['mention'][0]['screen_name']
...
except IndexError:
data = None # or handle this case in other way
我正在尝试使用以下命令从 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']
在其中一个 json 文件中 "mention" : [ ],
提及字段为空,它说
IndexError: 列表索引超出范围
错误很明显,但我该如何处理?
试试这个 -
mentions = d.get('text',{}).get('entities',{}).get('mention' ,[])
if len(mentions)>0:
print(mentions[0].get('screen_name',None))
else:
print(None)
您可以只使用 try/except
块。喜欢
try:
data = d['text']['entities']['mention'][0]['screen_name']
...
except IndexError:
data = None # or handle this case in other way