Array
Array

Reputation: 25

Method to download json object as json file python

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?

Upvotes: 2

Views: 707

Answers (1)

midori
midori

Reputation: 4837

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)

Upvotes: 2

Related Questions