开发者

How can I quickly dump a query result set into JSON?

import simplejson as json
results = Content.objects.filter(blah)
theresult_json = js开发者_如何学运维on.dumps(results)

This doesn't work!!


How about 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 is a python object. simplejson.dumps only works on python dict's/list's.

You need to convert your results object to a dict first. Either you do it manually like this:

l = [] 

for result in results:
    d = {
        'attr1': result.attr1,
        'attr2': result.attr2,
        ...
    }
    l.append(d)

theresult_json = simplejson.dumps(l)

or dynamically with a the objects __dict__ method, removing non JSON serializable attributes from it afterwards:

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)


Depending on what you're trying to do, you may also want to check out Piston. It has special Emitter classes for dumping your objects into a JSON format, XML format, etc... if you are building AJAX or API endpoints, the piston framework is incredibly useful.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜