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

使用Python(discord.py)实现JSON文件追加数据时按ID规则排序存储

实现按ID自动排序插入的修改方案

你的ID格式为前缀+yymmdd日期+序号,天然支持字符串自然排序,以下是两种适用不同场景的实现方案:


方案1:追加后全量排序(小数据量场景首选,代码改动最少)

如果你的JSON存储的条目数在数千条以内,直接追加后全量排序是最简单不易出错的方案,仅需要修改addpic函数中的JSON写入逻辑:

# 先把你原有代码里的变量名type改成img_type,避免覆盖Python内置的type函数
with open(f'image json/{img_type}.json', 'r') as fp:
    data = json.load(fp)
    # 构造新增数据对象
    new_item = {
      "id": img_id,
      "date": img_date,
      "time": img_time,
      "url": img_url
    }
    data[f'{img_type}'].append(new_item)
    # 按id字段升序排序,默认的字符串排序逻辑刚好匹配你需要的时间+序号顺序
    data[f'{img_type}'].sort(key=lambda item: item['id'])

with open(f'image json/{img_type}.json', 'w') as fp:
    json.dump(data, fp, indent = 2)

方案2:定位插入位置直接插入(大数据量场景更高效)

如果你的JSON条目数过万,全量排序会有性能损耗,可以用bisect模块直接找到插入位置写入,避免全列表排序:
首先在代码头部导入依赖:

import bisect

修改插入逻辑:

with open(f'image json/{img_type}.json', 'r') as fp:
    data = json.load(fp)
    new_item = {
      "id": img_id,
      "date": img_date,
      "time": img_time,
      "url": img_url
    }
    # 提取所有已有ID组成列表用于定位
    exist_ids = [item['id'] for item in data[f'{img_type}']]
    # 计算新ID对应的插入索引
    insert_idx = bisect.bisect_left(exist_ids, img_id)
    # 插入到对应位置
    data[f'{img_type}'].insert(insert_idx, new_item)

with open(f'image json/{img_type}.json', 'w') as fp:
    json.dump(data, fp, indent = 2)

额外优化建议

  • 生成ID时建议把序号补零,比如单日最多99条就补成2位:n = f"{num:02d}",避免后续出现序号10排在2前面的排序异常问题
  • 你原有的generateImgID函数中统计同日期条目数的逻辑有误,修改为:
# 原错误代码:result = Counter(data.values())[img_date]
# 修改后:
result = Counter(item['date'] for item in data[f'{img_type}'])[img_date]

内容的提问来源于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.04 01:15:00