如何循环 JSON 数据中的值?
How to loop over values in JSON data?
我有一些 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。
我把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()
您可以通过将其视为字典来实现这一点。尝试以下作为你的循环,你将能够提取你想要的结果:
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("-------------")
这是它将输出的内容的片段,日期为:
Date: 2018-07-02
1. open: 75.7500
2. high: 76.1517
3. low: 74.7800
4. close: 75.7700
5. volume: 3518838
-------------
这可能只是我的风格,但我更喜欢这种方法:
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()
做的代码更少每个值。尽管这在用途上是有限的,但如果您知道结构,则调试起来非常有效。
我喜欢编写称为 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
嘿,这里的主要主题不是 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))
真正领先于此,您可以编写一个函数来打印不是字典的值,例如:
def print_values(dictionary):
if isinstance(dictionary, dict):
for k, v in dictionary.items():
print(k)
print_values(v)
else:
print(dictionary)
再见!
我有一些 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。
我把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()
您可以通过将其视为字典来实现这一点。尝试以下作为你的循环,你将能够提取你想要的结果:
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("-------------")
这是它将输出的内容的片段,日期为:
Date: 2018-07-02
1. open: 75.7500
2. high: 76.1517
3. low: 74.7800
4. close: 75.7700
5. volume: 3518838
-------------
这可能只是我的风格,但我更喜欢这种方法:
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()
做的代码更少每个值。尽管这在用途上是有限的,但如果您知道结构,则调试起来非常有效。
我喜欢编写称为 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
嘿,这里的主要主题不是 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))
真正领先于此,您可以编写一个函数来打印不是字典的值,例如:
def print_values(dictionary):
if isinstance(dictionary, dict):
for k, v in dictionary.items():
print(k)
print_values(v)
else:
print(dictionary)
再见!