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
相关产品推荐
相关产品推荐

