【发布时间】:2011-06-07 14:46:54
【问题描述】:
import simplejson as json
results = Content.objects.filter(blah)
theresult_json = json.dumps(results)
这不行!!
【问题讨论】:
标签: javascript python django json
import simplejson as json
results = Content.objects.filter(blah)
theresult_json = json.dumps(results)
这不行!!
【问题讨论】:
标签: javascript python django json
http://docs.djangoproject.com/en/dev/topics/serialization/怎么样
?
from django.core import serializers
data = serializers.serialize('json', SomeModel.objects.all())
# it's pretty useful and quick.
data = serializers.serialize('json', SomeModel.objects.all(), fields=('foo','bar'))
【讨论】:
results 是一个 Python 对象。 simplejson.dumps 仅适用于 python dict's/list's。
您需要先将结果对象转换为字典。您可以像这样手动操作:
l = []
for result in results:
d = {
'attr1': result.attr1,
'attr2': result.attr2,
...
}
l.append(d)
theresult_json = simplejson.dumps(l)
或动态地使用对象__dict__ 方法,之后从中删除非 JSON 可序列化属性:
l = []
for result in results:
d = result.__dict__
# remove attributes from dict which are not JSON-serializable with del d[key]
l.append(d)
theresult_json = simplejson.dumps(l)
【讨论】:
根据您要执行的操作,您可能还想查看Piston。它具有特殊的 Emitter 类,用于将您的对象转储为 JSON 格式、XML 格式等......如果您正在构建 AJAX 或 API 端点,活塞框架非常有用。
【讨论】: