import json
with open('logs.json', 'r') as f:
logs = json.load(f)
sorted()函数按日志时间戳进行排序。sorted_logs = sorted(logs, key=lambda x: x['timestamp'])
with open('sorted_logs.json', 'w') as f:
json.dump(sorted_logs, f, indent=4)
完整代码示例:
import json
with open('logs.json', 'r') as f:
logs = json.load(f)
sorted_logs = sorted(logs, key=lambda x: x['timestamp'])
with open('sorted_logs.json', 'w') as f:
json.dump(sorted_logs, f, indent=4)
上一篇:按时间戳对对象进行排序