簡體   English   中英

如何使用部分日期將 json 拆分為多個文件

[英]How to split a json into multiple files using part of the date

我有一個包含天氣數據的大 json 文件。 每組都有時間戳。 現在我想將 json 拆分為多個文件,使用月份作為文件名:如 2021-10.json

數據如下所示:

[
{
    'dt': 1633651200,
    'temp': 11.09,
    'feels_like': 10.66,
    'pressure': 1030,
    'humidity': 92,
    'dew_point': 9.84,
    'uvi': 0,
    'clouds': 98,
    'visibility': 10000,
    'wind_speed': 2.05,
    'wind_deg': 26,
    'wind_gust': 3.26,
    'weather': [
        {'id': 804, 'main': 'Clouds', 'description': 'overcast clouds', 'icon': '04n'}
    ]
},
{
    'dt': 1633654800,
    'temp': 10.27,
    'feels_like': 9.75,
    'pressure': 1030,
    'humidity': 92,
    'dew_point': 9.03,
    'uvi': 0,
    'clouds': 100,
    'visibility': 10000,
    'wind_speed': 2.32,
    'wind_deg': 54,
    'wind_gust': 4.73,
    'weather': [
        {'id': 804, 'main': 'Clouds', 'description': 'overcast clouds', 'icon': '04n'}
    ]
},...

我做的第一件事是將時間戳轉換為日期。 到目前為止,我的代碼如下所示:

with open('data.json','r', encoding='utf8') as f:
# Read the file and convert it to a dictionary
d = json.load(f)
x = d['hourly']
rprint(x)
for json_obj in x:
    timestamp= json_obj['dt']
    dt_obj = datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')
    json_obj['dt'] = dt_obj
    rprint(dt_obj)
    filename=str(json_obj['dt'])+'.json'
    with open(filename, 'w') as out_json_file:
        json.dump(json_obj, out_json_file, indent=4)

有誰知道我如何將一天的所有條目放入一個 json 文件中。

先感謝您

您可以考慮創建一個臨時容器來重組和保存相關的月份數據,如下所示:

from collections import defaultdict

# ...open and parse json file

month_data = defaultdict(list)

for json_obj in hourly_data:
    timestamp = json_obj["dt"]
    # more useful to keep the datetime object as an object, not a string yet
    dt_obj = datetime.fromtimestamp(timestamp)

    json_obj["dt"] = dt_obj.strftime('%Y-%m-%d %H:%M:%S')
    # if you haven't used `defaultdict` before, it allows skipping some
    # boilerplate code when creating dict entries that may not exist
    month_data[dt_obj.strftime("%Y-%m")].append(json_obj)

# month: '2021-10' (key), json_data: list of hourly/day data (value)
for month, json_data in month_data.items():
    with open(f"{month}.json", "w") as json_outfile:
        json.dump(json_data, json_outfile, indent=4)

*編輯:

我看到您要求將每一天作為一個單獨的文件(您的代碼似乎按月執行)...我認為您可以將我的示例推斷為每天為一個 JSON 文件工作。 讓我知道你是否知道!

默認defaultdictPython 文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM