[英]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 all the 7 element of data['query']['results']['rate']
in conjunction.它打印出data['query']['results']['rate']
所有 7 个元素。
So I'm thinking this code should also 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')))
for d in data['query']['results']['rate'][:]
print(d)
Using for
to loop and print out each of the elements in data['query']['results']['rate']
.使用for
循环并打印出data['query']['results']['rate']
每个元素。
However this does not work and gives an error.但是,这不起作用并给出错误。
How can I iterate through json elements in Python?如何遍历 Python 中的 json 元素?
There is no need for [:]
to just iterate over the data:不需要[:]
来遍历数据:
for d in data['query']['results']['rate']:
print(d)
.. should work. .. 应该管用。 You're missing the :
.你错过了:
。
You can also use the .json()
method directly on the response from requests to decode the JSON into a python structure.您还可以直接在来自请求的响应上使用.json()
方法将 JSON 解码为 Python 结构。
Try this尝试这个
for d in data['query']['results']['rate']:
print(d)
instead of代替
for d in data['query']['results']['rate'][:]
print(d) #here ^ missed :
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.