使用json.dumps转换django queryset的datatime报…

2018-12-24 09:07:49来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

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

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

报错信息如下:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "D:\Python36\lib\json\__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "D:\Python36\lib\json\encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "D:\Python36\lib\json\encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "D:\Python36\lib\json\encoder.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}]'

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:网络爬虫之scrapy爬取某招聘网手机APP发布信息

下一篇:django加密解密api