Pixel Pixel - 2 months ago 12
JSON Question

Error when I parse a Json

I created a python app to parse a json API.

There is 3 endpoints and 1 of these worries me.

The endpoint is : http://coinmarketcap.northpole.ro/history.json?coin=PCN

My code :

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


When I try to get the
h['price']['usd']
I have this :

File "coinmarketcap.py", line 39, in getOrder
if h['price']['usd'] > price:
TypeError: string indices must be integers


When I do
print type(h)
it return unicode.

Answer Source

getHistory returns a dict, and when you iterate over it like this:

for h in self.getHistory(symbol):

you're iterating over the dict keys, not values.

To iterate over the value instead, use

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