python - 按JSON中的值对python中的JSON文件进行排序
问题描述
我正在尝试按高分对 JSON 进行排序,但这不起作用。我的 JSON:
{"players": [{"test": [{"high_score": 1000}]}, {"test1": [{"high_score": 1200}]}, {"test2": [{"high_score": 3000}]}]}
我的蟒蛇:
with open('score.json', "r") as json_file:
data = json.load(json_file)
json_file.close()
sorted_obj = data
sorted_obj['players'] = sorted(data['players'], key=lambda x: x['high_score'], reverse=True)
print(sorted_obj)
输出:
sorted_obj['players'] = sorted(data['players'], key=lambda x: x['high_score'], reverse=True)
KeyError: 'high_score''
我希望输出为:
{"players": [{"test2": [{"high_score": 3000}]}, {"test1": [{"high_score": 1200}]}, {"test": [{"high_score": 1000}]}]}
有谁知道如何解决这个问题?谢谢
解决方案
.close()
使用上下文管理器 ( with ...
)时无需调用。上下文管理器需要.close()
您,这就是重点。
您的 JSON 结构在很多方面都没有帮助。如果你不能改变它,这是可行的(我不会解释为什么,如果你无法弄清楚,那就把它当作你的数据结构严重错误的迹象,因为这些事情不应该这么难.)
with open('score.json', "r") as json_file:
data = json.load(json_file)
data['players'] = sorted(data['players'], key=lambda p: p[list(p.keys())[0]][0]['high_score'], reverse=True)
print(data)
有了更合理的输入数据结构,事情就变得简单了。
{"players": [
{"name": "test", "high_score": 1000},
{"name": "test1", "high_score": 1200},
{"name"; "test2", "high_score": 3000}
]}
和
data['players'] = list(sorted(data['players'], key=lambda p: p['high_score'], reverse=True))
推荐阅读
- php - Can't connect to database with error (HY000/2002): No connection could be made because the target machine主动拒绝它
- android - 无法从 Android 的 .bat 文件中获取在 shell 中输入的 su 命令
- python - 制作美国出生列表:如何在列表中将字符串设为 int
- r - 在R中的3dplots中更改轴标题和标签的方向?
- python - 在两个不同区域内拟合实验数据
- typescript - 在属性装饰器中获取属性类实例
- angular - ngfor 不显示
- java - 如何使用 Spring boot 修改 HttpServletResponse 以在 json 中包含一些标准属性?
- python-3.x - django 和 asyncio - 从远程 REST 端点异步获取数据
- ios - Firebase 和 Swift - 使用 UTC -7 保存的日期?