You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将含空值/无date键的JSON array按datetime排序并后置异常项

解决JSON数组按datetime排序并将异常项置于末尾的问题

问题分析

你的代码触发KeyError: 'date'是因为直接用x['date']访问键,当字典不存在date键时会报错;同时未正确处理date为None或空字符串的情况,导致排序逻辑失效。需要先统一处理这些异常场景,再执行排序。

修正后的代码

import datetime

example_response = [
    {
      "id": 2959,
      "original_language": "Permanent Job",
      "date": "2012-10-26",
      "absent": False
    },
    {
      "id": 8752,
      "original_language": "Intern Job",
      "date": "",
      "absent": True
    },
    {
      "adult": False,
      "id": 1300,
      "title": "Training Job",
      "date": "2020-07-25",
      "absent": False
    },
    {
      "adult": False,
      "id": 7807,
      "title": "Training Job",
      "absent": False
    },
]

def sorting_function(response):
    if response:
        sorted_data = sorted(
            response,
            key=lambda x: (
                # 标记异常项:无date键、date为None、空字符串(含纯空格)
                'date' not in x or x['date'] is None or (isinstance(x['date'], str) and x['date'].strip() == ""),
                # 正常项转datetime用于排序,异常项用极小值不影响顺序
                datetime.datetime.strptime(x['date'], "%Y-%m-%d") 
                if ('date' in x and x['date'] and isinstance(x['date'], str) and x['date'].strip()) 
                else datetime.datetime.min
            )
        )
        print(sorted_data)
        return sorted_data
    return response

# 调用测试
sorting_function(example_response)

关键逻辑说明

  1. 避免KeyError:通过'date' not in x判断键是否存在,替代直接索引x['date'];
  2. 异常项后置:把异常场景的第一个排序键设为True,正常项设为False。由于布尔值排序中True > False,异常项会自动排在末尾;
  3. 安全转换datetime:仅对有效date值执行strptime转换,异常项用datetime.min填充(第一个键已区分分组,不影响最终顺序);
  4. 函数通用性修正:原函数错误使用全局变量example_response,改为使用传入的response参数,保证函数可复用。

测试结果

排序后的数组顺序为:

  1. 含有效date(2012-10-26)的项
  2. 含有效date(2020-07-25)的项
  3. 含空date字符串的项
  4. 无date键的项

内容的提问来源于stack exchange,提问作者Vaneseaa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 01:05:24