首页 > 解决方案 > 解析 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} 值?

标签: pythonjson

解决方案


您可以使用.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)

推荐阅读