我正在寫一個小型的python應用程序,它會在livecoin.net上更新我的投資組合。我使用livecoin.net API以及coinmarketcap.com API。請求當從coinmarketcap.com API,如果你去它(https://api.coinmarketcap.com/v1/ticker/bitcoin/),該頁面被明確JSON,我得到這個錯誤:當請求的網站明顯是JSON時,沒有JSON對象可以被解碼
Traceback (most recent call last):
File "C:/Users/other/Desktop/livecoin.py", line 89, in <module>
cmcData = getCoinMarketCapData(balances)
File "C:/Users/other/Desktop/livecoin.py", line 22, in getCoinMarketCapData
cmcData = json.load(cmcResponse)
File "C:\Python27\lib\json\__init__.py", line 291, in load
**kw)
File "C:\Python27\lib\json\__init__.py", line 339, in loads
return _default_decoder.decode(s)
File "C:\Python27\lib\json\decoder.py", line 364, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python27\lib\json\decoder.py", line 382, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
我得到的頁面是很清楚JSON正如我剛纔所說,所以我真的不知道爲什麼會發生這種情況。任何人都可以幫我嗎?
我很清楚,這不是一個慈善代碼工作的網站,但我非常難過,這是我的計劃Z ...如果你願意幫忙,甚至不需要爲我編寫任何代碼,試着指出我錯在哪裏。謝謝:d
這裏是我的代碼:
# -*- coding: utf-8 -*-
import httplib
import urllib
import json
import hashlib
import hmac
from collections import OrderedDict
def getCoinMarketCapData(currencies):
returns = {}
cmcUrl = "api.coinmarketcap.com"
cmcMethod = "/v1/ticker/"
conn = httplib.HTTPSConnection(cmcUrl)
for item in currencies:
print item['name'].split(" ")[0].lower();
print cmcMethod+(item['name'].split(" ")[0].lower())
conn.request("GET", cmcMethod+(item['name'].split(" ")[0].lower()))
cmcResponse = conn.getresponse()
cmcData = json.load(cmcResponse)
c = {"name":item['name'].split(" ")[0], "currency":item['symbol'], "price_usd":cmcData[0]['price_usd'], "price_btc":cmcData[0]['price_btc'], "d1h":cmcData[0]['percent_change_1h'], "d24h":cmcData[0]['percent_change_24h'], "d7d":cmcData[0]['percent_change_7d'], "value":0.0}
returns[item['symbol']] = c
conn.close()
return returns
def getData(dataDict, method, server, key, secret):
encoded_data = urllib.urlencode(dataDict)
sign = hmac.new(secret, msg=encoded_data, digestmod=hashlib.sha256).hexdigest().upper()
headers = {"Api-key":key, "Sign":sign}
conn = httplib.HTTPSConnection(server)
conn.request("GET", method + '?' + encoded_data, '', headers)
response = conn.getresponse()
data = json.load(response)
conn.close()
return data
def outputLine(key, value, prefix, suffix):
spaces = ""
pslen = len(prefix) + len(suffix)
key = key.upper()
key = " " + key + ": "
keylen = len(key)
x = 35-keylen-pslen
for count in range(x-len(str(value))):
spaces += " "
return key + prefix + value + suffix + spaces
server = "api.livecoin.net"
balancesMethod = "/payment/balances"
coinInfoMethod = "/info/coinInfo"
api_key = "gEuyw7k4WvAhdXUmG36zHDksDZGR3fvq"
secret_key = "D4aTtN6tPxBqqDG24PFZ1238CMektp33"
responses = []
names = []
balances = []
namesJSON = getData([], coinInfoMethod, server, api_key, secret_key)['info']
for name in namesJSON:
names.append({"name":name['name'], "symbol":name['symbol']})
data = OrderedDict([])
d = getData(data, balancesMethod, server, api_key, secret_key)
responses.append(d)
for currency in responses[0]:
if currency['value'] > 0.0 and currency['type'] == 'total':
for name in names:
if name['symbol'] == currency['currency']:
currency['name'] = name['name']
balances.append(currency)
ownedCoins = []
for balance in balances:
ownedCoins.append({"name":balance['name'], "symbol":balance['currency']})
print ownedCoins
cmcData = getCoinMarketCapData(balances)
for balance in balances:
try:
cmcData[balance['currency']]['value'] = balance['value']
except:
continue
for coin in ownedCoins:
print coin
item = cmcData[str(coin)]
v = item['value']
v = "%f" % (v)
print "+-----------------------------------+"
print "|" + outputLine('currency', item['currency'], "", "") + "|"
print "|" + outputLine('amount owned', v, "", "") + "|"
print "|" + outputLine('price in usd', item['price_usd'], "$", "") + "|"
print "|" + outputLine('price in btc', item['price_btc'], u'\u20BF', "") + "|"
print "|" + outputLine('% change 1h', item['d1h'], "", "%") + "|"
print "|" + outputLine('% change 24h', item['d24h'], "", "%") + "|"
print "|" + outputLine('% change 7d', item['d7d'], "", "%") + "|"
print "+-----------------------------------+"
print "\n"
如果您執行'print(cmcResponse.read())',您會看到什麼打印? – alecxe
@alecxe謝謝,這非常有幫助! –