2017-07-17 81 views
0

我创建了一个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。

+0

所以,你已经证实,h是一个字符串,错误表示字符串索引必须是整数。您正试图使用​​其他字符串为该字符串编制索引。 – SuperShoot

+0

但我想要h ['price'] ['usd'],我该怎么做? – Pixel

+3

我假设'getHistory'返回一个字典,你就像这样迭代它:'for self.getHistory(symbol)'中的h。这给你字典_keys_,而不是_values_。在self.getHistory(symbol).values()'中试试'h。 –

回答

2

getHistory返回一个字典,当你遍历这样的:

for h in self.getHistory(symbol): 

你遍历字典,不

要通过价值迭代,而应使用

for h in self.getHistory(symbol).values(): # .itervalues() in python2 
1

@Pixel,我想你是假设的关键,这是不正确的for h in self.getHistory(symbol):返回值,则返回键。

尝试保存字典和按键映射,这样取,

json_data = self.getHistory(symbol) 
for h in json_data: 
    if json_data[h]['price']['usd'] > price: 
     ++count 

或检索字典中值的值,使用

for h in self.getHistory(symbol).values(): 
    if h['price']['usd'] > price: 
     ++count