我试图序列化一个 Python 列表,但得到了它不可序列化的错误。序列化 Long 整数列表是否有限制?
>>> ids=p.values_list('id',flat=True)
>>> ids
[335L, 468L, 481L, 542L, 559L, 567L, 609L]
>>> import simplejson as json
>>> str=json.dumps(ids)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Program Files\Google\google_appengine\lib\simplejson\simplejson\__ini
t__.py", line 265, in dumps
return _default_encoder.encode(obj)
File "C:\Program Files\Google\google_appengine\lib\simplejson\simplejson\encod
er.py", line 216, in encode
chunks = list(chunks)
File "C:\Program Files\Google\google_appengine\lib\simplejson\simplejson\encod
er.py", line 495, in _iterencode
o = _default(o)
File "C:\Program Files\Google\google_appengine\lib\simplejson\simplejson\encod
er.py", line 190, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: [335L, 468L, 481L, 542L, 559L, 567L, 609L] is not JSON serializable
>>>
最佳答案
“我正在尝试序列化一个 Python 列表……”
这实际上不是完整的故事。
您正在尝试序列化 ValuesListQuerySet
。
>>> type(ids)
<class 'django.db.models.query.ValuesListQuerySet'>
你可以
1. 转换为其他优秀答案中提到的 Python 列表,或者
2. 仅序列化 ID。
Django 有一种内置的方法来序列化 QuerySet
。
你只需要 ID,所以你可以使用 fields
克瓦格。
from django.core import serializers
data = serializers.serialize('json', YourEntity.objects.all(), fields=('id',))
关于python - 使用 json 序列化查询集的结果引发错误 :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6720121/