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

Python生成CHIP-0007格式JSON时SHA256哈希重复问题求解

解决CHIP-0007 JSON文件SHA256哈希重复问题

问题根源

你得到的哈希值 e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 是空字节序列的SHA256结果,说明生成的JSON文件实际为空,或者计算哈希时没有正确读取文件内容。

解决步骤

1. 排查JSON文件写入逻辑

先确认生成的JSON文件是否真的包含内容:

  • 检查文件写入模式,必须用'w'或'w+'而非只读模式
  • 验证CSV数据是否正确映射到CHIP-0007格式的JSON字段中,避免生成空字典/列表
  • 确保写入后调用了文件的flush()或close()方法,或者用with语句自动管理文件句柄

2. 正确计算文件SHA256哈希

使用二进制分块读取的方式计算哈希,确保读取完整文件内容:

import hashlib

def get_file_sha256(file_path):
    sha256 = hashlib.sha256()
    with open(file_path, "rb") as f:
        # 分块读取大文件,避免内存溢出
        while chunk := f.read(4096):
            sha256.update(chunk)
    return sha256.hexdigest()

3. 完整CSV转CHIP-0007 JSON示例

假设你的CSV数据如下(示例):

output_file,name,description,gender,collection_id
nft1.json,Warrior Bob,A fearless fighter,Male,col-001
nft2.json,Mage Alice,A spellcasting expert,Female,col-002

完整转换+哈希计算代码:

import csv
import json
import hashlib

def build_chip0007_data(row):
    # 严格遵循CHIP-0007格式构建数据
    return {
        "format": "CHIP-0007",
        "name": row["name"],
        "description": row["description"],
        "minting_tool": "Custom CSV Converter",
        "sensitive_content": False,
        "series_number": 1,
        "series_total": 10,
        "attributes": [
            {"trait_type": "Gender", "value": row["gender"]}
        ],
        "collection": {
            "name": "My NFT Collection",
            "id": row["collection_id"],
            "attributes": []
        }
    }

def calculate_sha256(file_path):
    sha256 = hashlib.sha256()
    with open(file_path, "rb") as f:
        while chunk := f.read(4096):
            sha256.update(chunk)
    return sha256.hexdigest()

# 处理CSV并生成带唯一哈希的JSON
with open("nft_data.csv", "r", encoding="utf-8") as csv_f:
    reader = csv.DictReader(csv_f)
    for row in reader:
        chip_data = build_chip0007_data(row)
        output_path = row["output_file"]
        
        # 写入JSON时固定格式,避免因缩进/编码差异导致哈希变化
        with open(output_path, "w", encoding="utf-8") as json_f:
            json.dump(chip_data, json_f, indent=2, ensure_ascii=False)
        
        # 计算并输出哈希
        file_hash = calculate_sha256(output_path)
        print(f"{output_path} -> SHA256: {file_hash}")

关键注意事项

  • JSON格式一致性:用json.dump时指定indent和ensure_ascii,保证不同文件的格式化规则完全一致,避免空格、换行差异影响哈希
  • 二进制读取:计算哈希必须用rb模式读取文件,防止编码转换改变字节流
  • 内容验证:生成后手动打开JSON文件,确认CSV数据已正确填充到对应字段中

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 16:25:31