2

I'm trying to extract the data from this json bitcoin api

stored in a json file. First I tried

import urllib, json
url = "http://api.coindesk.com/v1/bpi/currentprice.json"
response = urllib.urlopen(url)
data = json.loads(response.read())
print data

it worked at first but if I run it again, I get this error:

Traceback (most recent call last):
  File "btc_api.py", line 4, in <module>
    data = json.loads(response.read())
  File "/usr/lib/python2.7/json/__init__.py", line 338, 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 have to run the code periodically to get the newest currency and store it in a database. Can someone help me with this issue or any ideas how to do it better?

1 Answer 1

2

You can use requests with json method it provides:

import requests

url = "http://api.coindesk.com/v1/bpi/currentprice.json"
data = requests.get(url).json()

Though if you still want to use urllib use json.load:

import urllib
import json

url = "http://api.coindesk.com/v1/bpi/currentprice.json"
response = urllib.urlopen(url)
data = json.load(response)
Sign up to request clarification or add additional context in comments.

6 Comments

@Array you need to use load, not loads
Ok, i fixed that. Now I get AttributeError: 'str' object has no attribute 'read'. :/ and the other two methods throws errors to.
If I try the other methods, it gives me : raise ValueError("No JSON object could be decoded"
What str object and read? Can you use the exact code i gave you, it works without any problems
First I corrected loads in my original code with load. This gave me the str error. If I copy, paste your code into my .py file and run it, it throws No JSON object could be decoded. May it has something to do with my libs?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.