我有一些要循环播放的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可用。
答案 0 :(得分:2)
您可以通过将其视为字典来实现。尝试以下操作作为循环,您将能够提取所需的结果:
lodash
这是有关日期输出的摘要:
for key,value in json_data['Time Series (Daily)'].items():
print("Date: " + key) #This prints the Date
print("1. open: " + value["1. open"])
print("2. high: " + value["2. high"])
print("3. low: " + value["3. low"])
print("4. close: " + value["4. close"])
print("5. volume: " + value["5. volume"])
print("-------------")
答案 1 :(得分:1)
我采用了json_data['Time Series (Daily)']
并将其分配给它自己的变量,以使其更易于在for循环中引用。
然后,当您遍历循环时,必须引用该变量以访问日期键中的值。
data = json_data['Time Series (Daily)']
for item in data:
print(item)
print("open", data[item]["1. open"])
print("high", data[item]["2. high"])
print("low", data[item]["3. low"])
print("close", data[item]["4. close"])
print("vloume", data[item]["5. volume"])
print()
答案 2 :(得分:1)
嘿,这里的主要主题不是JSON本身,而是字典,它是Python中的内置类型。我不完全知道您要如何处理这些数据,但是访问数据的一种方法是访问字典附带的方法。像dict.keys(),dict.items()和dict.values()一样,您可以查询一些文档。我将举一个有关如何访问数据的示例,希望对您有所帮助。
url=requests.get('https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=TGT&apikey=RYFJGY3O92BUEVW4')
url_json = url.json() # This data is actually of dict type
for k,j in url_json['Time Series (Daily)'].items():
print(k)
for m, n in j.items(): # This data are a nested dictionary
print('{} : {}'.format(m, n))
要真正做到这一点,您可以编写一个函数,如果不是dict,则输出值,例如:
def print_values(dictionary):
if isinstance(dictionary, dict):
for k, v in dictionary.items():
print(k)
print_values(v)
else:
print(dictionary)
再见!
答案 3 :(得分:0)
这可能只是我的风格,但我更喜欢这种方法:
for item in json_data['Time Series (Daily)']:
open, high, low, close, volume = sorted(item).values()
print('\n\t'.join([item.keys()[0], open, high, low, close, volume]))
通过这种方式,您已经在一行中将值分配给了开,高,低...,并且易于使用。
我还使它在一行代码中将所有值打印在换行符(带有缩进)上,与每个值进行print()
相比,这使代码面条更少。尽管这是有限的,但如果知道结构,它的使用将非常有效地调试。
答案 4 :(得分:0)
我喜欢编写称为data-driven的代码,因为这通常使以后的更改变得更容易。
在这种情况下,可以这样做:
SERIES_KEY = 'Time Series (Daily)'
VALUE_KEYS = '1. open', '2. high', '3. low', '4. close', '5. volume'
longest_key = max(len(key) for key in VALUE_KEYS)
daily = json_data[SERIES_KEY]
for date, values in sorted(daily.items()):
print(date)
for key in VALUE_KEYS:
print(' {:{width}} : {}'.format(key, values[key], width=longest_key))
print()
输出:
2018-11-19
1. open : 79.9300
2. high : 80.4000
3. low : 77.5607
4. close : 77.7900
5. volume : 9126929
2018-11-20
1. open : 67.9900
2. high : 71.5000
3. low : 66.1500
4. close : 69.6800
5. volume : 15573611