0

OK, I have this code where i'm getting some json back from instagram's api....

      instaINFO = requests.get("https://api.instagram.com/v1/media/%s?access_token=xyz" % instaMeID).json()
      print instaINFO
      #pdb.set_trace()
      MSG = {'fromEMAIL': uEmail, 'toCHANNELID': channelID, 'timeSENT': uTi    me, 'profilePIC': instaINFO['data']['user']['profile_picture'],'userNAME': instaINFO[    'data']['user']['username'], 'msgBODY': instaINFO['data']['caption']['text']}

but sometimes

       instaINFO['data']['caption']['text'] 

might not have any data. and I get this back.

      MSG = {'fromEMAIL': uEmail, 'toCHANNELID': channelID, 'timeSENT': uTime,
      'profilePIC': instaINFO['data']['user']['profile_picture'],'userNAME':
      instaINFO['data']['user']['username'], 'msgBODY': instaINFO['data']['caption']
      ['text']}
      TypeError: 'NoneType' object is not subscriptable

error checking or defensive coding is not my speciality... So how do I make the code pass if a json value = None

I've tried to do this but to no avail...

      if instaINFO['data']['caption']['text'] == None:
       pass
3
  • Is the data key empty or the caption key? Commented Aug 7, 2013 at 7:45
  • What do you want to happen if the key is missing? Also (as an aside) checking for the None singleton should not be done with == but with is. Commented Aug 7, 2013 at 7:52
  • if the key is missing, I want the value filled with "" and the script to keep on running. the script stops running if someone's instagram caption isn't filled. Commented Aug 7, 2013 at 7:53

1 Answer 1

1

If you want to fill the MSG dictionary as much as possible, you need to add each value separately:

MSG = {'fromEMAIL': uEmail, 'toCHANNELID': channelID, 'timeSENT': uTime}
try:
    MSG['profilePIC'] = instaINFO['data']['user']['profile_picture']
except TypeError:
    MSG['profilePIC'] = ""
try:
    MSG['userNAME'] = instaINFO['data']['user']['username']
except TypeError:
    MSG['userNAME'] = ""
try:
    MSG['msgBODY'] = instaINFO['data']['caption']['text']
except TypeError:
    MSG['msgBODY'] = ""

or, to avoid violating the DRY principle:

MSG = {'fromEMAIL': uEmail, 'toCHANNELID': channelID, 'timeSENT': uTime}
for mkey, subdict, ikey in (('profilePIC', 'user', 'profile_picture'), 
                            ('userNAME', 'user', 'username'),
                            ('msgBODY', 'cpation', 'text')):
    try:
        MSG[msgkey] = instaINFO['data'][subdict][instakey]
    except TypeError:
        MSG[msgkey] = ""
Sign up to request clarification or add additional context in comments.

1 Comment

stackoverflow.com/questions/15009276/… would this answer help my cause?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.