[英]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 文件工作。 让我知道你是否知道!
默认defaultdict
的Python 文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.