You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解析含动态键的JSON并转换为Pandas DataFrame?

解析特殊结构JSON并导入Pandas DataFrame

针对你提供的嵌套结构JSON,由于data字段下的键为动态用户ID,每个ID下又以时间戳为键存储记录,直接使用json_normalize无法直接解析出目标格式。以下是手动拆解并导入DataFrame的方案:

步骤1:导入依赖库

import pandas as pd
import json

步骤2:加载JSON数据

# 从文件读取JSON
with open('your_json_file.json', 'r', encoding='utf-8') as f:
    raw_data = json.load(f)

# 若JSON是字符串形式,直接用下面的方式加载
# raw_data = json.loads(your_json_string)

步骤3:拆解嵌套结构并收集记录

records = []

# 遍历每个用户ID对应的数据集
for user_id, user_entries in raw_data['data'].items():
    # 遍历用户下的每条时间戳记录,跳过无用的__collections__字段
    for timestamp, entry_details in user_entries.items():
        if timestamp == '__collections__':
            continue
        # 合并用户ID、时间戳与记录详情
        processed_record = {
            'id': user_id,
            'time': timestamp,
            **entry_details  # 展开author、new等字段
        }
        records.append(processed_record)

步骤4:转换为DataFrame并调整列顺序

df = pd.DataFrame(records)
# 按照期望的列顺序重新排列
df = df[['id', 'time', 'author', 'new', 'old', 'property', 'sender']]

执行上述代码后,生成的DataFrame将完全匹配你期望的格式。

内容的提问来源于stack exchange,提问作者user3362705

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 16:20:37