当请求的网站明显是JSON时,没有JSON对象可以被解码

我正在写一个小型的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"

回答:

我已经能够使用下面的代码加载JSON:

import urllib, json 

url = "https://api.coinmarketcap.com/v1/ticker/bitcoin/"

response = urllib.urlopen(url)

data = json.loads(response.read())

当我试图用json.load代替json.loads我有一个错误(与你的不同),但它可能会给你一个关于可能出错的提示。

以上是 当请求的网站明显是JSON时,没有JSON对象可以被解码 的全部内容, 来源链接: utcz.com/qa/259636.html

回到顶部