Организация файлов JSON при добавлении через Python (discord.py) ввод

#python #json #discord.py #append

Вопрос:

В настоящее время я создаю бота на Discord.py прямо сейчас, и одна из команд принимает входные данные, которые будут сохранены в файле JSON. Один из ключей-это своего рода идентификатор, связанный с каждым объектом, и его формат в основном представляет собой своего рода буквенно-цифровой код. Примерная версия JSON выглядит следующим образом:

 {
  "data": [
    {
      "id": "tbg210915-1",
      "date": "September 15, 2021",
      "time": "21:09",
      "url": "https://example.com"
    },
    {
      "id": "tbg210915-2",
      "date": "September 15, 2021",
      "time": "21:09",
      "url": "https://example2.com"
    },
    {
      "id": "tbg210917-1",
      "date": "September 17, 2021",
      "time": "01:33",
      "url": "https://example3.com"
    },
  ]
}
 

Я хочу , чтобы произошло следующее: если я введу новый объект, чей идентификатор tbg210916-1 , он будет добавлен между tbg210915-2 «и tbg210917-1 «.

Вот как команда работает прямо сейчас, чтобы вы знали, как они в настоящее время добавляются:

 # function to generate the aforementioned id
def generateImgID(file, type, img_date):
  # turning input data type into abbreviated codes
  convert_list = {...} # a list of types one can input and what their corresponding code would be
    
  if type in convert_list.keys():
    m = convert_list[type]

  # converting Month dd, yyyy format to yymmdd 
  d = datetime.datetime.strptime(img_date, '%B %d, %Y').strftime('%y%m%d')

  # that number at the end thingy signifying what nth pic that is in a given day
  new = open(file)
  data = json.load(new)

  result = Counter(data.values())[img_date]
  if result == 0:
    num = 1
  else:
    num = result   1
  
  n = str(num)

  return f'{m}{d}-{n}'

# command to add new pic to database of json files
@client.command()
async def addpic(ctx):
  def check(message):
    return message.author == ctx.author and message.channel == ctx.channel

  ... # here is basically a multi-step input process then for the bot to ask the user what to input

# adding all input to json
  with open(f'image json/{type}.json', 'r') as fp:
    data = json.load(fp)

    data[f'{type}'].append({
      "id": img_id,
      "date": img_date,
      "time": img_time,
      "url": img_url
    })
  
  with open(f'image json/{type}.json', 'w') as fp:
    json.dump(data, fp, indent = 2)

  await ctx.send(embed = successembed)
 

Ответ №1:

Вы можете попробовать сортировать список каждый раз, когда добавляете новый элемент, т. е.:

 data.append(newelement)
data.sort(key=lambda x: x['id'])
 

Который будет сортировать список «данные» на месте