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"}]
阅读 13.9k
2 个回答

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

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}]

首先题目中有个错误:"time":"201503012"应该是:"time":"20150312
另外按照时间排序的话,我经常这样写:

from datetime import datetime
def my_cmp(a,b):
    a_time = datetime.strptime(a,'%Y%m%d')
    b_time = datetime.strptime(b,'%Y%m%d')
    return 1 if a > b  else -1 if a < b else 0
json_array=[{"time":"20150312","value":"c"},        
{"time":"20150301","value":"a"},
{"time":"20150305","value":"b"}]

print sorted(json_array, cmp=my_cmp, key=lambda x:x['time'])
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏