简体   繁体   中英

Reading values from Json file

I am trying to read an attribute from a Json file using this: d['text']['entities']['mention'][0]['screen_name']

Json File

{
    "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" : [ ],
        },

    }
}

I am trying to load many json files in Neo4J Database using py2neo library.

While accesing d['text']['entities']['mention'][0]['screen_name'] in one of the json file in which "mention" : [ ], mention field is empty it says

IndexError: list index out of range

Error is pretty obvious but how should I handle this?

You could just use try/except block. Like

try:
  data = d['text']['entities']['mention'][0]['screen_name']
  ...
except IndexError:
  data = None # or handle this case in other way

try this -

   mentions = d.get('text',{}).get('entities',{}).get('mention' ,[])
   if len(mentions)>0:
        print(mentions[0].get('screen_name',None))
   else:
        print(None)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM