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?
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With