Another question about JSON

Peter Otten __peter__ at web.de
Fri Sep 13 09:24:25 EDT 2013


Anthony Papillion wrote:

> Hello Again Everyone,
> 
> I'm still working to get my head around JSON and I thought I'd done so
> until I ran into this bit of trouble. I'm trying to work with the
> CoinBase API. If I type this into my browser:
> 
> https://coinbase.com/api/v1/prices/buy
> 
> I get the following JSON returned
> 
> {"subtotal":{"amount":"128.00","currency":"USD"},"fees":[{"coinbase":
{"amount":"1.28","currency":"USD"}},{"bank":
{"amount":"0.15","currency":"USD"}}],"total":
{"amount":"129.43","currency":"USD"},"amount":"129.43","currency":"USD"}
> 
> So far, so good. Now, I want to simply print out that bit of JSON (just
> to know I've got it) and I try to use the following code:
> 
> returnedJSON = json.loads('https://coinbase.com/api/v1/prices/buy')
> print returnedString
> 
> 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
> 
> 
> I'm very confused since the URL is obviously returned a JSON string. Can
> anyone help me figure this out? What am I doing wrong?

Let's see:

>>> help(json.loads)
Help on function loads in module json:

loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, 
parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
    Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON
    document) to a Python object.
[...]

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.




More information about the Python-list mailing list