我创建了一个python应用程序来解析一个json API。
有3个端点和1个这些担心我。
端点是:http://coinmarketcap.northpole.ro/history.json?coin=PCN当我解析一个JSON时出错
我的代码:
def getHistory(self, coin):
endpoint = "history.json?year=2017&coin=PCN"
data = urllib2.urlopen(self.url + endpoint).read()
data = json.loads(data)['history']
return data
def getOrder(self):
for c in self.getCoinsList():
res = []
symbol = c['symbol']
price = self.getCoinPrice(symbol)
count = 0
count_days = len(self.getHistory(symbol))
for h in self.getHistory(symbol):
if h['price']['usd'] > price:
++count
percent_down = count_days/count * 100
line = {'symbol': symbol, 'price': price, 'percent_down': percent_down}
res.append(line)
return res
当我试图让h['price']['usd']
我有这样的:
File "coinmarketcap.py", line 39, in getOrder
if h['price']['usd'] > price:
TypeError: string indices must be integers
当我做print type(h)
它返回Unicode。
所以,你已经证实,h是一个字符串,错误表示字符串索引必须是整数。您正试图使用其他字符串为该字符串编制索引。 – SuperShoot
但我想要h ['price'] ['usd'],我该怎么做? – Pixel
我假设'getHistory'返回一个字典,你就像这样迭代它:'for self.getHistory(symbol)'中的h。这给你字典_keys_,而不是_values_。在self.getHistory(symbol).values()'中试试'h。 –