I've been using the API in python for the past few months to look at data. Today, my code broke because the result was no longer valid JSON. It appears that the Zero Width No Break Space character/Byte Order Mark (U+FEFF) is appearing as the first character in the response.
A python script to replicate:
import requests
url="https://api.stackexchange.com/2.2/sites/?filter=%21%2AL1%2AAY-85YllAr2%29&pagesize=1&page=1"
response = requests.get(url)
response.text
This returns the following:
u'\ufeff{"items":[{"site_state":"normal","api_site_parameter":"stackoverflow","name":"Stack Overflow"}],"has_more":true,"quota_max":300,"quota_remaining":282}'
Can that leading character be removed? It looks like this was reported on stackapps already, though the question didn't contain enough detail.
The server also says that it is returning application/json
data (I've formatted this to look nicer):
>>> response.headers
{
'content-length': '142',
'content-encoding': 'gzip',
'cache-control': 'private',
'access-control-allow-credentials': 'false',
'date': 'Thu, 03 Jul 2014 02:10:26 GMT',
'access-control-allow-origin': '*',
'access-control-allow-methods': 'GET, POST',
'content-type': 'application/json; charset=utf-8'
}
And response.json()
errors, as expected with invalid json
>>> response.json()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\requests\models.py", line 763, in json
return json.loads(self.text, **kwargs)
File "C:\Python27\lib\json\__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "C:\Python27\lib\json\decoder.py", line 365, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python27\lib\json\decoder.py", line 383, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
application/json
andresponse.json()
fails.FEFF
a UTF-16 BOM?? (UTF-8 is0xEF,0xBB,0xBF
?) try setting theresponse.encoding
to UTF-16.? (This looks like a malformed or mismatched BOM bug. Doesn't Python seamlessly handle proper BOM's??)Python source code u"\uFEFF"
, which is exactly what I'm seeing in my response. Forcing the encoding to UTF-16 didn't help..decode()
might work...text/plain
orapplication/json
). Python apparently isn't as tolerant?