开发者

In Django : How to serialize dict object to json?

开发者 https://www.devze.com 2023-01-03 10:22 出处:网络
I have this very ba开发者_如何学Csic problem, >>> from django.core import serializers >>> serializers.serialize(\"json\", {\'a\':1})

I have this very ba开发者_如何学Csic problem,

>>> from django.core import serializers
>>> serializers.serialize("json", {'a':1})
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/lib/pymodules/python2.6/django/core/serializers/__init__.py", line 87, in serialize
    s.serialize(queryset, **options)
  File "/usr/lib/pymodules/python2.6/django/core/serializers/base.py", line 40, in serialize
    for field in obj._meta.local_fields:
AttributeError: 'str' object has no attribute '_meta'
>>> 

How can this be done?


Also, since you seem to be using Python 2.6, you could just use the json module directly:

import json
data = json.dumps({'a': 1})


from django.utils import simplejson
data = simplejson.dumps({'a': 1})


Libraries like json or simplejson are not really cool for the purpose of serializing django objects, when you can use the serializer from django.core in your views:

from django.core import serializers


def json_for_model_instance(request, pk):       
    instance = YourModel.objects.get(pk=pk)
    serialized_instance = serializers.serialize('json', [instance, ])

    return HttpResponse(serialized_instance, content_type="application/json")
0

精彩评论

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

关注公众号