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

discord.py对JSON文件排序时保留父键不覆盖全文件的方法咨询

解决方案

问题原因

你当前代码仅将排序后的sample数组单独写入JSON文件,丢失了外层包含sample键的字典结构,才会导致外层父键消失。

修正后的代码

@client.command()
async def add(ctx):
 # ... 原有获取img_id、img_date等输入的代码保持不变
  with open('sample.json', 'r') as fp:
    data = json.load(fp)

    data['sample'].append({
      "id": img_id,
      "date": img_date,
      "time": img_time,
      "url": img_url
    })

    # 将排序后的数组重新赋值给原字典的sample字段
    data['sample'] = sorted(data['sample'], key=lambda x: x['id'])
  
  with open('sample.json', 'w') as fp:
    # 写入完整的data字典,保留所有外层结构
    json.dump(data, fp, indent = 2)

补充说明

该修改方案除了可以保留sample父键外,若你的JSON文件后续新增了其他根级字段,也会完整保留不会被覆盖。

内容的提问来源于stack exchange,提问作者ak.luizui

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 19:18:03