此代码有效:
#!/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'][:])
它会打印出data['query']['results']['rate']
的所有7个元素。
所以我认为这段代码也应该有效:
#!/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')))
for d in data['query']['results']['rate'][:]
print(d)
使用for
循环并打印出data['query']['results']['rate']
中的每个元素。
但是这不起作用并且出错。
如何在Python中迭代json元素?
答案 0 :(得分:1)
[:]
无需迭代数据:
for d in data['query']['results']['rate']:
print(d)
..应该有用。您错过了:
。
您还可以直接对请求的响应使用.json()
方法将JSON解码为python结构。
答案 1 :(得分:-1)
试试这个
for d in data['query']['results']['rate']:
print(d)
而不是
for d in data['query']['results']['rate'][:]
print(d) #here ^ missed :