python按值排序json列表

标签 python json lambda sorting

我有一个由 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/

相关文章:

python - pytz.utc 和 dt.timezone.utc 有什么区别?

python - 以受控方式运行数十个 Scrapy 蜘蛛

python - 如何编写Xpath进行动态值传递?

javascript - 维基百科 API 沙箱,根据用户输入进行搜索

json - 在 Svelte 的 main.js 中导入本地 json

python - 使用 exec() 从字符串运行 lambda 函数

c# - 如何获取作为函数传递的匿名方法的参数值?

python - 如何在 AWS elastic beanstalk 上部署结构化 Flask 应用程序

java - 使用 Java 将数据存储在 JSON 文件中

javascript - 使用 CoffeeScript 从对象数组中选择一个字段