簡體   English   中英

如何按字母順序排序此json文件?

[英]How do I sort this json file alphabetically?

我正在學習如何在python中使用json,我想知道如何按字母順序對json文件進行排序。 這是文件:

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

我希望數據列表中的項目通過“文本”鍵按字母順序排列,然后將結果保存到新的json文件中。 感謝您的幫助 :)

使用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) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM