python - 如何按字母顺序对这个 json 文件进行排序?
问题描述
我正在学习如何将 json 与 python 一起使用,我想知道如何按字母顺序对 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)
推荐阅读
- pascal - 以编程方式检查软件包是否安装在 Lazarus IDE 中
- magento - magento 2 | 客户帐户被暂时禁用
- javascript - 即使节点高于 8.5,performance.now() 也未定义
- c# - Unity c# - 将玩家移动到他面对的方向(而不是全局空间)
- python - Tensorflow Keras 保持每批次的损失
- python - Python - 如何通过请求向 API 发出 PATCH 请求
- r - 基于作为字符串的第一列在 R 中聚合数据框
- r - 将 R 中的多个列组合成一个新的向量列(最好是 tidyr 解决方案)
- python - python elasticsearch elasticsearch.exceptions.SSLError: ConnectionError([SSL: WRONG_VERSION_NUMBER] 版本号错误 (_ssl.c:1056))
- c++ - 如何使用户可以将变量添加到类并在 C++ 中选择类型?