我创建了一个用于解析json API的python应用程序
有3个端点,其中1个让我担心。
端点是:http://coinmarketcap.northpole.ro/history.json?coin=PCN
我的代码:
#!/bin/bash
cd /home
touch somefile
/usr/bin/expect<<FILETRANSFER
spawn scp -r -P remoteServerPort somefile remoteServerIP:/home
expect "assword:"
send "MyPassWord\r"
interact
FILETRANSFER
echo "It's done"
当我试图获得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
时,它会返回unicode。
答案 0 :(得分:2)
getHistory
返回一个字典,当你像这样迭代它时:
for h in self.getHistory(symbol):
你正在迭代dict 键,而不是值。
要迭代该值,请使用
for h in self.getHistory(symbol).values(): # .itervalues() in python2
答案 1 :(得分: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