如何用pandas json_normalize解析含数字键的嵌套JSON生成DataFrame
解析带动态数字键的JSON并生成指定结构DataFrame
我需要用pandas的json_normalize工具解析JSON文件,最终生成指定结构的DataFrame后写入Excel(写入代码已准备好)。遇到的问题是JSON里timestamp字段下的键都是动态变化的数字,不知道该怎么设置json_normalize的record_path参数。
期望的DataFrame结构
Timestamp BatteryVoltage GridCurrent GridVoltage InverterCurrent InverterVoltage .... ....
现有代码(无法实现需求)
import json import datetime import pandas as pd from pandas.io.json import json_normalize with open('test.json') as data_file: data = json.load(data_file) df = pd.json_normalize(data['timestamp'])
示例JSON数据
{"timestamp": { "1636987025": { "batteryVoltage": 28.74732, "gridCurrent": 3.68084, "gridVoltage": 230.64401, "inverterCurrent": 2.00471, "inverterVoltage": 224.18573, "solarCurrent": 0, "solarVoltage": 0, "tValue": 1636987008 }, "1636987085": { "batteryVoltage": 28.52959, "gridCurrent": 3.40046, "gridVoltage": 230.41367, "inverterCurrent": 1.76206, "inverterVoltage": 225.24319, "solarCurrent": 0, "solarVoltage": 0, "tValue": 1636987136 }, "1636987146": { "batteryVoltage": 28.5338, "gridCurrent": 3.37573, "gridVoltage": 229.27209, "inverterCurrent": 2.11128, "inverterVoltage": 225.51733, "solarCurrent": 0, "solarVoltage": 0, "tValue": 1636987136 }, "1636987206": { "batteryVoltage": 28.55535, "gridCurrent": 3.43365, "gridVoltage": 229.47604, "inverterCurrent": 1.98594, "inverterVoltage": 225.83649, "solarCurrent": 0, "solarVoltage": 0, "tValue": 1636987264 } } }
解决方案
因为timestamp下的键是动态数字,直接解析原结构会把这些数字作为列名,不符合需求。我们可以先把数据整理成json_normalize能处理的列表格式:
代码实现
import json import pandas as pd from pandas.io.json import json_normalize with open('test.json') as data_file: data = json.load(data_file) # 把动态时间戳键转为Timestamp字段,和对应数据合并成字典列表 records = [{"Timestamp": ts, **data_dict} for ts, data_dict in data['timestamp'].items()] # 解析整理后的列表 df = json_normalize(records) # 重命名列名,匹配期望的首字母大写格式 df = df.rename(columns={ 'batteryVoltage': 'BatteryVoltage', 'gridCurrent': 'GridCurrent', 'gridVoltage': 'GridVoltage', 'inverterCurrent': 'InverterCurrent', 'inverterVoltage': 'InverterVoltage' }) # 按需保留指定列并调整顺序 df = df[['Timestamp', 'BatteryVoltage', 'GridCurrent', 'GridVoltage', 'InverterCurrent', 'InverterVoltage']] # 写入Excel(你已有的代码) # df.to_excel('output.xlsx', index=False)
关键说明
- 列表推导式
[{"Timestamp": ts, **data_dict} ...]:把每个动态时间戳作为单独的Timestamp字段,同时展开对应的数据字典,让每个元素都包含所有所需字段,适合json_normalize解析 - 列名重命名:将原始JSON中的小写列名转换为你期望的首字母大写格式
- 列选择:可根据需求筛选需要的列并调整顺序,确保和目标DataFrame结构一致
内容的提问来源于stack exchange,提问作者gansub
相关产品推荐
相关产品推荐

