首页 > 解决方案 > 如何按字母顺序对这个 json 文件进行排序?

问题描述

我正在学习如何将 json 与 python 一起使用,我想知道如何按字母顺序对 json 文件进行排序。这是文件:

{
  "data": [
    {
      "text": "first sentence",
      "entities": [
      ]
    },
    {
      "text": "second sentence",
      "entities": [
      ]
    },
    {
      "text": "third sentence",
      "entities": [
      ]
    },
    {
      "text": "fourth sentence",
      "entities": [
      ]
    }
  ]
}

我希望数据列表中的项目按“文本”键按字母顺序排列,然后将该结果保存到新的 json 文件中。感谢您的帮助 :)

标签: pythonjson

解决方案


使用 sorted 按文本字段排序

import json

with open('yourfile.json') as f:
    json_data = json.load(f)
    data_list = json_data['data']

json_data['data'] = sorted(data_list, key=lambda k: k['text'])

with open('newfile.json') as f:
    json.dump(json_data) 

推荐阅读