How to iterate through json elements using for in Python -
this code works:
#!/usr/bin/env python3 import urllib.request, json url = urllib.request.urlopen('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22dkknok%2ceurnok%2cgbpnok%2cisknok%2cnoknok%2cplnnok%2cseknok%22)&format=json&env=store%3a%2f%2fdatatables.org%2falltableswithkeys') data = json.loads(url.read().decode(url.info().get_content_charset('utf-8'))) print(data['query']['results']['rate'][:])
it prints out 7 element of data['query']['results']['rate']
in conjunction.
so i'm thinking code should work:
#!/usr/bin/env python3 import urllib.request, json url = urllib.request.urlopen('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22dkknok%2ceurnok%2cgbpnok%2cisknok%2cnoknok%2cplnnok%2cseknok%22)&format=json&env=store%3a%2f%2fdatatables.org%2falltableswithkeys') data = json.loads(url.read().decode(url.info().get_content_charset('utf-8'))) d in data['query']['results']['rate'][:] print(d)
using for
loop , print out each of elements in data['query']['results']['rate']
.
however not work , gives error.
how can iterate through json elements in python?
there no need [:]
iterate on data:
for d in data['query']['results']['rate']: print(d)
.. should work. you're missing :
.
you can use .json()
method directly on response requests decode json python structure.
Comments
Post a Comment