python中怎么对json数组按json的某个字段进行排序

我有一个json数组,我想对数组以json中的某个字段排序,这个如何做到?
比如:

json_array=[{"time":"20150312","value":"c"},        
{"time":"20150301","value":"a"},
{"time":"20150305","value":"b"}]

python是否提供相应api方法对以上数组的“time”字段按升序排列,最后数组的结果是:

json_array=[{"time":"20150301","value":"a"},
{"time":"20150305","value":"b"},
{"time":"20150312","value":"c"}]
小花花
2个月前提问
1 个回答
  • 董俊俊

    还有种更优雅直观的方法,一行就可以搞定:

    json_array = [{"time":20150312,"value":"c"}, {"time":20150301,"value":"a"}, {"time":20150305,"value":"b"}]
    
    json_array.sort(key = lambda x:x["time"])

    运行结果:

    print(json_array)
    [{'value': 'a', 'time': 20150301}, {'value': 'b', 'time': 20150305}, {'value': 'c', 'time': 20150312}]
撰写答案
  • 相似问题