简体   繁体   English

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

[英]In Django : How to serialize dict object to json?

I have this very basic 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: 此外,由于您似乎使用的是Python 2.6,因此您可以直接使用json模块:

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: 当您在视图中使用django.core中的序列化程序时,像jsonsimplejson这样的库对于序列化django对象来说并不是很酷:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM