Handle JSON Decode Error when nothing returned

后端 未结 2 952
囚心锁ツ
囚心锁ツ 2020-11-30 00:17

I am parsing json data. I don\'t have an issue with parsing and I am using simplejson module. But some api requests returns empty value. Here is my example:

2条回答
  •  醉酒成梦
    2020-11-30 01:08

    There is a rule in Python programming called "it is Easier to Ask for Forgiveness than for Permission" (in short: EAFP). It means that you should catch exceptions instead of checking values for validity.

    Thus, try the following:

    try:
        qByUser = byUsrUrlObj.read()
        qUserData = json.loads(qByUser).decode('utf-8')
        questionSubjs = qUserData["all"]["questions"]
    except ValueError:  # includes simplejson.decoder.JSONDecodeError
        print 'Decoding JSON has failed'
    

    EDIT: Since simplejson.decoder.JSONDecodeError actually inherits from ValueError (proof here), I simplified the catch statement by just using ValueError.

提交回复
热议问题