【问题标题】:Organizing JSON files while appending through Python (discord.py) input在通过 Python (discord.py) 输入追加时组织 JSON 文件
【发布时间】:2021-11-11 23:49:26
【问题描述】:

我目前正在 Discord.py 上制作一个机器人,其中一个命令接受将存储到 JSON 文件中的输入。其中一个键是与每个对象关联的一种 ID,其格式基本上是一种字母数字代码。 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"
    },
  ]
}

我想要发生的是,如果我输入一个 id 为tbg210916-1 的新对象字典,它将附加在tbg210915-2tbg210917-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)

【问题讨论】:

    标签: python json discord.py append


    【解决方案1】:

    您可以尝试在每次添加新元素时对列表进行排序,即:

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

    这将对列表“数据”就地

    进行排序

    【讨论】:

      猜你喜欢
      • 2016-06-22
      • 1970-01-01
      • 2022-01-08
      • 2017-08-12
      • 1970-01-01
      • 1970-01-01
      • 2013-09-29
      • 1970-01-01
      • 2021-08-14
      相关资源
      最近更新 更多