0

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?

Aman Kumar
  • 137
  • 1
  • 1
  • 8

2 Answers2

0

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
kvorobiev
  • 5,012
  • 4
  • 29
  • 35
-1

try this -

   mentions = d.get('text',{}).get('entities',{}).get('mention' ,[])
   if len(mentions)>0:
        print(mentions[0].get('screen_name',None))
   else:
        print(None)
tom
  • 3,720
  • 5
  • 26
  • 48
  • 2
    string wouldn't produce `IndexError: list index out of range`. Also, you don't convert it into a "json object", but *python objects*. JSON is a text serialization format. – juanpa.arrivillaga Jun 05 '17 at 18:00
  • @juanpa.arrivillaga , I have tested this code and it is working , looks like json is wrong and having some extra ',' in the json . – tom Jun 05 '17 at 18:16
  • Yes, I know the code works, but this answer doesn't address the OP's problem, which is a list throwing an `IndexError`. Indeed, the code in the OPs question *works*, so obviously, this isn't the issue. – juanpa.arrivillaga Jun 05 '17 at 18:22
  • Again **this has nothing to do with the error the OP is encountering, which is caused by indexing a list out of range**. There was a typo in the sample data the OP provided, but that isn't the root issue. – juanpa.arrivillaga Jun 05 '17 at 18:24
  • Just got to know the real problem. **Please see the edited version of problem.** – Aman Kumar Jun 05 '17 at 18:35
  • @juanpa.arrivillaga , can you see it now ? thanks for help! – tom Jun 05 '17 at 18:45