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

如何在写入JSON前排序数据?解决str与list类型排序报错问题

解决JSON数据排序时str与list类型比较的错误

问题场景

执行json_dic.sort(key= lambda x: x['lastLogonTimestamp'], reverse= False)排序时,抛出TypeError: '<' not supported between instances of 'str' and 'list'错误。原因是lastLogonTimestamp字段存在两种数据类型:空值以列表形式存在(如"lastLogonTimestamp": []),有效日期以字符串形式存在(如"lastLogonTimestamp": "2021-02-15 06:35:34.363626+00:00"),不同类型无法直接参与排序比较。

输入数据示例

json_dic = [
    {
        "lastLogonTimestamp": [],
        "sAMAccountName": "batman"
    },
    {
        "lastLogonTimestamp": "2021-02-15 06:35:34.363626+00:00",
        "sAMAccountName": "superman"
    },
    {
        "lastLogonTimestamp": "2022-09-12 04:08:01.311201+00:00",
        "sAMAccountName": "green-lantern"
    },
    {
        "lastLogonTimestamp": "2022-09-13 04:48:43.275908+00:00",
        "sAMAccountName": "wonder-woman"
    },
    {
        "lastLogonTimestamp": [],
        "sAMAccountName": "hulk"
    }
]

解决代码

自定义排序key函数,统一处理两种类型的字段值,实现正常排序:

def lastLogonTimestamp_sort(value):
    timestamp = value['lastLogonTimestamp']
    is_str = isinstance(timestamp, str)
    return is_str, str(timestamp)

json_dic.sort(key=lastLogonTimestamp_sort, reverse=False)

代码说明

  1. 类型分组:通过is_str判断字段类型,布尔值False(列表类型)会排在True(字符串类型)之前,实现空值条目统一前置;
  2. 统一比较基准:将所有字段值转为字符串,列表[]转为"[]",日期字符串保持原样。ISO格式的日期字符串本身可通过字符串比较得到正确的时间顺序,因此排序结果符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 17:42:49