python sort list of json by value

前端 未结 4 1084
北海茫月
北海茫月 2020-12-28 12:33

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

sample JSON file:

{ \"page\": { \"url\": \"url1\", \"         


        
4条回答
  •  伪装坚强ぢ
    2020-12-28 13:09

    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)
    

提交回复
热议问题