Search code examples
pythonjsonfilepython-importpy2neo

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?


Solution

  • 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