Python pandas深层嵌套JSON转CSV的末列标准化问题求解
嵌套JSON转CSV标准化解决方案
import pandas as pd import json # 读取JSON文件 with open('Performance_Interface_data.json') as f: data = json.load(f) # 多层嵌套展开 df = pd.json_normalize( data['abcd-performance:output']['performance'], # 指定要展开的深层嵌套数组路径 record_path = ['sample', 'attribute'], # 指定需要保留的上层公共字段 meta = [ ['sample', 'objectId'], ['sample', 'ifName'], ['sample', 'timeStamp'], ['sample', 'type'], ['sample', 'invalid'] ], # 字段名拼接用下划线 sep = '_' ) # 重命名参数、值列匹配预期格式 df.rename( columns = { 'parameter': 'sample_attribute_parameter', 'value': 'sample_attribute_value' }, inplace = True ) # 调整列顺序符合要求 df = df[['sample_objectId', 'sample_ifName', 'sample_timeStamp', 'sample_type', 'sample_invalid', 'sample_attribute_parameter', 'sample_attribute_value']] # 导出为分号分隔的CSV df.to_csv('output.csv', sep=';', index=False) print(df.columns) print(df)
运行后将自动展开所有嵌套的attribute字段,每个参数单独生成一行,列名完全匹配要求的格式。每个原始sample条目会根据attribute数组的长度生成对应行数的记录,不会丢失数据。
内容的提问来源于stack exchange,提问作者Ritesh Jain
相关产品推荐
相关产品推荐

