转储时如何对 JSON 值进行排序?

How do I sort a JSON value while dumping?

我正在尝试 dump/sort JSON 特定时间格式的值。

在提问之前,我看了各种问题,例如:

  1. (这实际上是尝试了一些东西后的问题)
  2. Sorting a JSON file by a certain key(最具体的一个,虽然我没有使用任何名称键)
  3. JSON output sorting in Python(没有真正帮助)

我的 JSON 的结构如下:

{
  "Arthur": "12/12",
  "Lisa": "10/12"
}

日期格式为dd/mm。在这件事上,我想在 12/12 之前有 10/12。然而,这不应该在读出 JSON 时发生,而是在 dumping 值时发生。

我尝试使用的代码:

with open(f"saved_date.json", "r", encoding='utf-8') as f:
    data = json.load(f) # Just so you can see how I read out the JSON


with open('saved_date.json', 'w', encoding='utf-8') as fpp:
    json.dump(data, fpp, indent=2, sort_keys=True) # Sorting the keys does not work obviously

with open('saved_date.json', 'w', encoding='utf-8') as fpp:
    json.dump(sorted(data, key=lambda x: datetime.strptime(date, "%d/%m")), fpp, indent=2) # date is individually given in the format mentioned above 

也许这里有人可以看出哪里出了问题,或者给我提示如何更好地构建它。 我目前将 JSON 更新为:

        try:
            data[f"{author}"] = date # author is the one using/executing the code
        except:
            new = {author: date}
            data.update(new)
data = {'Arthur': '12/12', 'Lisa': '10/12'}

with open('saved_date.json', 'w', encoding='utf-8') as f:
    json.dump(dict(sorted(data.items(), key=lambda x: x[1])), f, indent=2)

输出:

{
  "Lisa": "10/12",
  "Arthur": "12/12"
}

因为你的日期是dd/mm格式,你不能按字母顺序排序;您需要先对 mm 部分进行排序,然后对 dd 部分进行排序:

data = {'Arthur': '12/12', 'Lisa': '10/12', 'Joe': '31/05'}

json.dumps(dict(sorted(data.items(), key=lambda x: x[1].split('/')[::-1])), indent=2)

输出:

{
  "Joe": "31/05",
  "Lisa": "10/12",
  "Arthur": "12/12"
}