• python 使用json.dumps转换django queryset的datatime报错问题解决


    转换成json时使用的方法如下:

    json.dumps(list(models.userlist.objects.values("vu")))

    报错信息如下:

    Traceback (most recent call last):
      File "<console>", line 1, in <module>
      File "D:Python36libjson\__init__.py", line 231, in dumps
        return _default_encoder.encode(obj)
      File "D:Python36libjsonencoder.py", line 199, in encode
        chunks = self.iterencode(o, _one_shot=True)
      File "D:Python36libjsonencoder.py", line 257, in iterencode
        return _iterencode(o, 0)
      File "D:Python36libjsonencoder.py", line 180, in default
        o.__class__.__name__)
    TypeError: Object of type 'datetime' is not JSON serializable

    解决方案如下:

    >>> from django.core.serializers.json import DjangoJSONEncoder 

    >>> import json 
     
    
    
    >>> json.dumps(list(models.userlist.objects.values()), cls=DjangoJSONEncoder) 

    '[{"vu": 1, "username": "jwh", "password": "0e01234c7d1c41dda9376d21467330bd", "isVip": true, "vipEndtime": "2018-02-20T10:53:01", "is_whitelist": false, "subscription_status": false}, {"vu": 3, "username": "jiang", "password": "", "isVip": false, "vipEndtime": "2018-09-03T16:42:13", "is_whitelist": false, "subscription_status": false}, {"vu": 4, "username": "jiangwenhui", "password": "", "isVip": false, "vipEndtime": "2018-09-05T14:22:37.911", "is_whitelist": false, "subscription_status": false}, {"vu": 5, "username ": "test", "password": "", "isVip": false, "vipEndtime": "2018-09-05T14:36:47", "is_whitelist": false, "subscription_status": false}]'
  • 相关阅读:
    xml配置文件使用-读取、转换
    .NET 4.0 缓存
    jQuery分页插件pagination.js 笔记
    Spring源码
    Shell编程(字符串篇)
    Linux DNS 相关
    Shell将命令执行结果写入文件
    Linux安装GCC
    Linux网络安全
    产品经理基础
  • 原文地址:https://www.cnblogs.com/jiangwenhui/p/10168979.html
Copyright © 2020-2023  润新知