afs*_*hin 11 python django serialization json
我试图序列化一个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
>>>
Run Code Online (Sandbox Code Playgroud)
ber*_*nie 19
"我正在尝试序列化一个Python列表......"
这实际上并不完整.
您正在尝试序列化ValuesListQuerySet.
>>> type(ids)
<class 'django.db.models.query.ValuesListQuerySet'>
Run Code Online (Sandbox Code Playgroud)
您可以
1.转换为其他优秀答案中提到的Python列表,或者
2.仅序列化ID.
Django有一种内置的序列化方式QuerySet.
而你只需要ID就可以使用fieldskwarg.
from django.core import serializers
data = serializers.serialize('json', YourEntity.objects.all(), fields=('id',))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14218 次 |
| 最近记录: |