Mam plik składa się z JSON, każda linia, i chcesz posortować plik przez odwrócenie update_time.Lista sortowania python json według wartości
przykładowy plik 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": {} }
chcą wyjście:
{ "page": { "url": "url1", "update_time": "1415387875"}, "other_key": {} }
{ "page": { "url": "url3", "update_time": "1415384938"}, "other_key": {} }
{ "page": { "url": "url2", "update_time": "1415381963"}, "other_key": {} }
mój kod:
#!/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
Kod działa poprawnie z przykładowego pliku JSON, ale jeśli JSON nie ma "update_time", spowoduje zgłoszenie wyjątku KeyError. Czy istnieją sposoby, aby to zrobić?
jak przypisać plik json do linii tak, że musi dynamicznie, jeśli mam 1 milion linii, to nie załaduje się poprawnie, dlatego –