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

Python处理pandas数据框逐行生成指定嵌套字典并导出为独立JSON文件

解决方案

你可以直接使用Python标准库的json模块结合行遍历逻辑实现需求,完整可运行代码如下:

第一步:导入依赖

import pandas as pd
import json

第二步:定义单行结构转换函数

def build_nft_meta(row):
    # 初始化基础返回结构
    result = {
        "name": row["name"],
        "image": row["image"],
        "attributes": []
    }
    # 配置所有属性列名,也可以动态过滤:attribute_cols = [col for col in df.columns if col not in ["name", "image"]]
    attribute_cols = ["background", "tshirt", "eagle", "hair", "face", "hat"]
    for trait_col in attribute_cols:
        trait_value = row[trait_col]
        # 跳过空值:可根据你实际的空值表现调整判断逻辑,比如空字符串、NaN、None都覆盖
        if pd.notna(trait_value) and str(trait_value).strip() != "":
            result["attributes"].append({
                "trait_type": trait_col,
                "value": trait_value
            })
    return result

第三步:遍历行导出独立JSON文件

# 替换为你自己的DataFrame加载逻辑
# df = pd.read_csv("你的数据源文件路径.csv")

for index, row in df.iterrows():
    # 生成每行的结构化数据
    meta_data = build_nft_meta(row)
    # 自定义文件名规则,此处用行序号命名,你可以调整为用name字段命名等
    file_name = f"nft_meta_{index}.json"
    with open(file_name, "w", encoding="utf-8") as f:
        # escape_forward_slashes=False 解决链接斜杠转义问题,indent=2实现格式化输出
        json.dump(meta_data, f, ensure_ascii=False, indent=2, escape_forward_slashes=False)

问题对应解决说明

  • 嵌套结构生成问题:通过自定义函数逐行逐属性判断组装,完全匹配你需要的attributes列表结构,空值自动跳过
  • 链接转义问题:放弃使用Pandas自带的to_json方法,改用标准库json模块的dump方法,通过escape_forward_slashes=False参数关闭正斜杠自动转义,保留https链接的//格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 07:18:01