23 Aug 2013

No JSON object could be decoded: line 1 column 0 (char 0)

I have written a python code which makes the HTTP requests to fetch the json data.
The json data seems like :
{    
  "items": [
          {
            "question_id": 18384375,
            "answer_id": 18388044,
            "creation_date": 1377195687,
            "last_activity_date": 1377195687,
            "score": 0,
            "is_accepted": false,
            "owner": {
                "user_id": 1745001,
                "display_name": "Ed Morton",
                "reputation": 10453,
                "user_type": "registered",
                "link": "http://stackoverflow.com/users/1745001/ed-morton"
                 }
          },
      ]
}

Code : 

>>url="https://api.stackexchange.com/2.1/answers?order=desc&sort=activity&site=stackoverflow"
>>obj = urllib.urlopen(url)
>>response_str = obj.read()
>>response_json = simplejson.loads(response_str)

Error : 

The last line above shoots following  error.
JSONDecodeError at /
No JSON object could be decoded: line 1 column 0 (char 0)

when i tried to change the simplejson to json object for loads() then following  error occurred
ValueError at /
No JSON object could be decoded

I tried to check the json format using the Jsonlint which gave me error :


The error suggested that problem is of encoding type of the response . Then i inspects the response information like
    >>obj.info()
         Server: nginx
         Date: Fri, 23 Aug 2013 04:51:01 GMT
         Content-Type: application/json; charset=utf-8
         Connection: close
         Cache-Control: private
         Content-Encoding: gzip
         Access-Control-Allow-Origin: *
         Access-Control-Allow-Methods: GET, POST
         Access-Control-Allow-Credentials: false
         Content-Length: 2334

Solution:

The problems seems to be of content Content-Encoding of the response which is gzip format and simplejson or json  is failed to correctly parse that. After many searches on stackoverflow i found the following the solution(s) of problem.
Solution: better to use requests object.

1) using only requests
   import requests
   response_json = requests.get(url).json()


2)  using only requests with simplejson or json.
     import requests
     response = requests.get(url)
     response_json = simplejson.loads(response.text)
     print response_json

Above both the codes  returning the correct Content-Encoding for json.
>>reposnse_json.encoding
     utf-8
>>response_json.headers['content-type']
    "application/json; charset=utf8'



No comments:

Post a Comment