使用json.dumps转换django queryset的datatime报错问题解决
程序员文章站
2022-05-02 07:53:24
转换成json时使用的方法如下: 报错信息如下: 解决方案如下: ......
转换成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}]'