如何在JSON文件中按字母顺序按一个字符串对列表排序

2024-05-21 04:09:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要按照“category”字符串的字母顺序对产品列表进行排序

我试过.sort(),但每次都会出错

这是我最接近成功的一次:

import json

with open("broken_database.json", "r", encoding="utf-8") as file:
    broken_database = json.load(file)
    for case in broken_database:
        case["category"] = sorted(case["category"], key = lambda category: category)

with open("broken_database.json", "w", encoding="utf-8") as file:
    json.dump(broken_database, file, indent=2)

print(broken_database)

我希望得到这样的东西:

{
    "id": 1911864,
    "name": "Møuse Gæmer Predætør ¢estus 510 Føx Pretø",
    "price": "699",
    "category": "Acessórios"
  },
 {
    "id": 9746439,
    "name": "Høme Theæter LG ¢øm ßlu-ræy 3D, 5.1 ¢ænæis e 1000W",
    "quantity": 80,
    "price": 2199,
    "category": "Eletrônicos"
  },

先是“Acessórios”,然后是“Eletrônicos”,但我得到的是:

{
    "id": 3500957,
    "name": "Monitor 29 LG FHD Ultrawide com 1000:1 de contraste",
    "quantity": 18,
    "price": 1559.4,
    "category": [
      "E",
      "c",
      "e",
      "i",
      "l",
      "n",
      "o",
      "r",
      "s",
      "t",
      "\u00f4"
    ]
  },
  {
    "id": 1911864,
    "name": "Mouse Gamer Predator cestus 510 Fox Preto",
    "price": 699.0,
    "category": [
      "A",
      "c",
      "e",
      "i",
      "o",
      "r",
      "s",
      "s",
      "s",
      "\u00f3"
    ],
    "quantity": 0
  }
]

我不知道我在这方面哪里出了问题,.sort()命令并不像通常那样工作,而且因为这是我第一次尝试在JSON文件中使用它,我猜这里缺少了一些东西


Tags: nameidjsonwithopensortpricedatabase
1条回答
网友
1楼 · 发布于 2024-05-21 04:09:52

你就快到了。尝试使用键功能对原始列表进行排序:

import json

with open("broken_database.json", "r", encoding="utf-8") as file:
    broken_database = json.load(file)
    broken_database.sort(key=lambda case: case["category"])

with open("broken_database.json", "w", encoding="utf-8") as file:
    json.dump(broken_database, file, indent=2)

print(broken_database)

相关问题 更多 >