首页 > 解决方案 > 按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}]}]}

有谁知道如何解决这个问题?谢谢

标签: pythonjsonsorting

解决方案


.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))

推荐阅读