python按值对json排序列表 [英] python sort list of json by value

查看:493
本文介绍了python按值对json排序列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由JSON组成的文件,每行一行,并且想通过反向的update_time对文件进行排序.

I have a file consists of JSON, each a line, and want to sort the file by update_time reversed.

示例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异常.有没有例外的方法可以做到这一点?

The code works fine with sample JSON file, but if a JSON has no 'update_time', it will raise KeyError exception. Are there non-exception ways to do this?

推荐答案

编写一个使用try...except处理KeyError的函数,然后将此函数用作key参数而不是lambda.

Write a function that uses try...except to handle the KeyError, then use this as the key argument instead of your 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排序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆