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

使用Pandas扁平化含LIST值的嵌套JSON并生成指定列结构

实现代码

你需要先提取外层JSON的所有值,再将每个条目下的atributes列表手动转换为键值对后合并基础字段,即可得到目标结构:

import json
import pandas as pd

# 读取本地JSON文件
with open("file.t", "r", encoding="utf-8") as f:
    raw_data = json.load(f)

flatten_list = []
for item in raw_data.values():
    # 提取基础字段
    base = {"name": item["name"]}
    # 将属性列表转为键值对,同时自动去除属性名首尾空格(适配原数据中Rarity Score末尾的空格)
    attr_map = {attr["trait_type"].strip(): attr["value"] for attr in item["atributes"]}
    # 合并两个字典加入结果列表
    flatten_list.append({**base, **attr_map})

# 生成DataFrame并按指定列顺序排列,缺失字段自动填充NaN
target_cols = ['name','Apple Count', 'Body Type', 'Background', 'Body Texture', 'Stone Type', 'Leaf Texture', 'Apple Texture', 'Animal','Rarity Score']
result_df = pd.DataFrame(flatten_list).reindex(columns=target_cols)

结果说明

没有Animal属性的条目会自动在对应列填充NaN,完全匹配你需要的列结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 17:24:01