【发布时间】:2019-04-23 13:01:01
【问题描述】:
我有一些 JSON 想要循环(简化):
{
"Meta Data": {
"1. Information": "Daily Prices (open, high, low, close) and Volumes",
"2. Symbol": "TGT",
"3. Last Refreshed": "2018-11-20 14:50:52",
"4. Output Size": "Compact",
"5. Time Zone": "US/Eastern"
},
"Time Series (Daily)": {
"2018-11-20": {
"1. open": "67.9900",
"2. high": "71.5000",
"3. low": "66.1500",
"4. close": "69.6800",
"5. volume": "15573611"
},
"2018-11-19": {
"1. open": "79.9300",
"2. high": "80.4000",
"3. low": "77.5607",
"4. close": "77.7900",
"5. volume": "9126929"
}
}
日期是我事先不知道的值并且每天都在变化,所以我想循环它们并用开盘价、最高价、最低价等打印日期。到目前为止,我所能做的就是循环覆盖日期并打印它们,但是当我尝试获取其他值时,对于 JSON 读取来说是新手,我使用以下代码失败了:
import urllib.parse
import requests
code = 'TGT'
main_api = ('https://www.alphavantage.co/query? function=TIME_SERIES_DAILY&symbol=' +
code + '&apikey=RYFJGY3O92BUEVW4')
url = main_api + urllib.parse.urlencode({'NYSE': code})
json_data = requests.get(url).json()
#print(json_data)
for item in json_data['Time Series (Daily)']:
print(item)
for item in json_data[item]:
print(item)
我也试过这样做:
for v in json_data:
print(v['1. open'])
而不是嵌套,但它仍然不起作用。 在这两次尝试中,我都得到了同样的错误:
Traceback (most recent call last):
File "jsonreader.py", line 26, in <module>
for item in item['Time Series (Daily)'][item]:
TypeError: string indices must be integers
所以有人知道如何遍历所有日期并从中找出开盘价、最高价、最低价等吗?
完整版 JSON 可用here。
【问题讨论】:
标签: python json loops nested-loops