我有一个由 JSON 组成的文件,每个文件都有一行,并且想按 update_time 倒序对文件进行排序。
示例 JSON 文件:
{ "page": { "url": "url1", "update_time": "1415387875"}, "other_key": {} }
{ "page": { "url": "url2", "update_time": "1415381963"}, "other_key": {} }
{ "page": { "url": "url3", "update_time": "1415384938"}, "other_key": {} }
想要输出:
{ "page": { "url": "url1", "update_time": "1415387875"}, "other_key": {} }
{ "page": { "url": "url3", "update_time": "1415384938"}, "other_key": {} }
{ "page": { "url": "url2", "update_time": "1415381963"}, "other_key": {} }
我的代码:
#!/bin/env python
#coding: utf8
import sys
import os
import json
import operator
#load json from file
lines = []
while True:
line = sys.stdin.readline()
if not line: break
line = line.strip()
json_obj = json.loads(line)
lines.append(json_obj)
#sort json
lines = sorted(lines, key=lambda k: k['page']['update_time'], reverse=True)
#output result
for line in lines:
print line
该代码适用于示例 JSON 文件,但如果 JSON 没有“update_time”,它将引发 KeyError 异常。有没有异常(exception)的方法来做到这一点?
最佳答案
编写一个使用 try...except
处理 KeyError
的函数,然后将其用作 key
参数而不是您的 lambda .
def extract_time(json):
try:
# Also convert to int since update_time will be string. When comparing
# strings, "10" is smaller than "2".
return int(json['page']['update_time'])
except KeyError:
return 0
# lines.sort() is more efficient than lines = lines.sorted()
lines.sort(key=extract_time, reverse=True)
关于python按值排序json列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26924812/