简体   繁体   English

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

[英]How do I sort a JSON value while dumping?

I am trying to dump/sort JSON values by a specific time format.我正在尝试按特定时间格式转储/排序 JSON 值。

Before asking, I have looked as various questions such as:在提问之前,我已经查看了各种问题,例如:

  1. When I tried to sort a list, I got an error 'dict' object has no attribute (This was actually a problem after trying some things) 当我尝试对列表进行排序时,出现错误 'dict' object has no attribute (这实际上是在尝试了一些事情之后出现的问题)
  2. Sorting a JSON file by a certain key (Most specific one, though I do not use any name keys) 按某个键对 JSON 文件进行排序(最具体的一个,尽管我不使用任何名称键)
  3. JSON output sorting in Python (Did not really help) Python 中的 JSON 输出排序(没有真正帮助)

The structure of my JSON is the following:我的 JSON 结构如下:

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

The date format is dd/mm .日期格式为dd/mm I want to have 10/12 before 12/12 in that matter.在这件事上,我想在12/12之前有10/12 This should not however happen while reading out the JSON, but rather while dumping the value.然而,这不应该在读取 JSON 时发生,而是在转dumping时发生。

The codes I tried to use:我尝试使用的代码:

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 

Maybe someone here can see what went wrong or give me tips on how to better structure it.也许这里有人可以看到出了什么问题,或者给我一些关于如何更好地构建它的提示。 I currently update the JSON with:我目前使用以下内容更新 JSON:

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

Because your dates are in dd/mm format, you cannot sort them alphabetically;因为您的日期是dd/mm格式,所以您不能按字母顺序对它们进行排序; you need instead to sort on the mm part, then the dd part:您需要对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)

Output:输出:

{
  "Joe": "31/05",
  "Lisa": "10/12",
  "Arthur": "12/12"
}
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)

Output:输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM