python - 解析 json 文件以获取其中每个日期的特定字段
问题描述
我有一堆看起来像这样的 json 文件:
{
"Meta Data": {
"1. Information": "Daily Prices (open, high, low, close) and Volumes",
"2. Symbol": "AAPL",
"3. Last Refreshed": "2021-03-12",
"4. Output Size": "Compact",
"5. Time Zone": "US/Eastern"
},
"Time Series (Daily)": {
"2021-03-12": {
"1. open": "120.4000",
"2. high": "121.1700",
"3. low": "119.1600",
"4. close": "121.0300",
"5. volume": "88105050"
},
"2021-03-11": {
"1. open": "122.5400",
"2. high": "123.2100",
"3. low": "121.2600",
"4. close": "121.9600",
"5. volume": "103026514"
},
"2021-03-10": {
"1. open": "121.6900",
"2. high": "122.1700",
"3. low": "119.4500",
"4. close": "119.9800",
"5. volume": "111943326"
}
}
}
他们一直回到“2020-10-19”。我的最终目标是计算每个字段的平均值(开盘价、最高价、最低价、收盘价、成交量)并绘制它,显示每个字段低于其平均值的次数,我想我知道如何获得每个文件所需的值,通过使用 Fstrings:
opening = data['Time Series (Daily)'][f'{date}'][f'{field}']
我的问题是:有没有一种简单的方法来解析 json 文件,以获取时间序列中每个日期的 {date} 和 {field} 值?
解决方案
您可以使用.keys()
字典的功能来获取键列表。这是一个计算开盘平均值的示例:
dates = data['Time Series (Daily)'].keys()
openingSum = 0
for date in dates:
opening = data['Time Series (Daily)'][date][f'{field}']
openingSum += float(opening)
openingAverage = openingSum / len(prices)
推荐阅读
- java - 如何通过休眠环境审计两个具有一对一关系的表?
- powershell - 通过删除文件扩展名(.csv 或 .xlsx)后的时间戳来重命名文件名
- c# - 当我销毁我的对象时,在不同的位置创建新的对象
- php - 集成 windows 活动目录 PHP Web 应用程序
- sql-server - SQL Server 2012 - 文本列 - 将一列拆分为多行
- linux-kernel - 在新机器上为现有代码库设置交叉编译器
- linux - Linux bash 如何在复制命令中使用通配符的结果作为文件名
- c# - 在 Unity 中扫描蓝牙
- vb.net - 可以批量移入多个文件吗
- rhel - 显式声明 lib 时出现 UnsatisfiedLinkError 异常