Another question about JSON

Anthony Papillion papillion at gmail.com
Fri Sep 13 11:05:24 EDT 2013


On 09/13/2013 08:24 AM, Peter Otten wrote:
> Anthony Papillion wrote:
> 
>> And I get a traceback that says: No JSON object could be decoded. The
>> specific traceback is:
>>
>> Traceback (most recent call last):
>>   File "coinbase_bot.py", line 31, in <module>
>>     getCurrentBitcoinPrice()
>>   File "coinbase_bot.py", line 28, in getCurrentBitcoinPrice
>>     returnedString = json.loads(BASE_API_URL + '/prices/buy')
>>   File "/usr/lib/python2.7/json/__init__.py", line 326, in loads
>>     return _default_decoder.decode(s)
>>   File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
>>     obj, end = self.raw_decode(s, idx=_w(s, 0).end())
>>   File "/usr/lib/python2.7/json/decoder.py", line 384, in raw_decode
>>     raise ValueError("No JSON object could be decoded")
>> ValueError: No JSON object could be decoded
> 
> So json.loads() expects its first argument to b valid json, no a URL.
> You have to retrieve the data using other means before you can deserialize 
> it:
> 
> data = urllib2.urlopen(...).read()
> returned_json = json.loads(data)
> 
> Replacing ... with something that works is left as an exercise. (It seems 
> that you have to use a Request object rather than a URL, and that the 
> default "Python-urllib/2.7" is not an acceptable user agent.

Thank you Peter! That was all I needed. So here's the code I came up
with that seems to work:

req = urllib2.Request(BASE_URL + '/prices/buy')
req.add_unredirected_header('User-Agent', USER_AGENT)
resp = urllib2.urlopen(req).read()
data - json.loads(resp)
return data['amount']

Thank you for the help!

Anthony






-- 
Anthony Papillion
XMPP/Jabber:      cypherpunk at patts.us
OTR Fingerprint:  4F5CE6C07F5DCE4A2569B72606E5C00A21DA24FA
SIP:              17772471988 at callcentric.com
PGP Key:          0xE1608145




More information about the Python-list mailing list