Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle JSON Decode Error when nothing returned

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:

{ "all" : {     "count" : 0,     "questions" : [     ]     } } 

This is the segment of my code where I parse the json object:

 qByUser = byUsrUrlObj.read()  qUserData = json.loads(qByUser).decode('utf-8')  questionSubjs = qUserData["all"]["questions"] 

As I mentioned for some requests I get the following error:

Traceback (most recent call last):   File "YahooQueryData.py", line 164, in <module>     qUserData = json.loads(qByUser)   File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/simplejson/__init__.py", line 385, in loads     return _default_decoder.decode(s)   File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/simplejson/decoder.py", line 402, in decode     obj, end = self.raw_decode(s, idx=_w(s, 0).end())   File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/simplejson/decoder.py", line 420, in raw_decode     raise JSONDecodeError("No JSON object could be decoded", s, idx) simplejson.decoder.JSONDecodeError: No JSON object could be decoded: line 1 column 0 (char 0) 

What would be the best way to handle this error?

like image 678
add-semi-colons Avatar asked Dec 05 '11 04:12

add-semi-colons


People also ask

How do I fix JSON decode error?

JSONDecodeError: Extra data" occurs when we try to parse multiple objects without wrapping them in an array. To solve the error, wrap the JSON objects in an array or declare a new property that points to an array value that contains the objects.

Can JSON loads return None?

loads() method. The loads() method returns the null equivalent of Python, which is None. To work with json data in Python, import the json library. Then define a json object consists of a null value, which we will convert into None.

How do I decode a JSON file?

You just have to use json_decode() function to convert JSON objects to the appropriate PHP data type. Example: By default the json_decode() function returns an object. You can optionally specify a second parameter that accepts a boolean value. When it is set as “true”, JSON objects are decoded into associative arrays.


1 Answers

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.

like image 168
Tadeck Avatar answered Nov 16 '22 23:11

Tadeck