在Django中:如何将dict对象序列化为json?

时间:2010-06-10 00:34:26

标签: python django json serialization

我有这个非常基本的问题,

>>> 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'
>>> 

如何做到这一点?

3 个答案:

答案 0 :(得分:14)

此外,由于您似乎使用的是Python 2.6,因此您可以直接使用json模块:

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

答案 1 :(得分:6)

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

答案 2 :(得分:0)

jsonsimplejson这样的库在序列化django对象时并不是很酷,当您可以在视图中使用django.core中的序列化程序时:

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")