In Django: how to serialize a dict object for 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 I do that?

+4
source share
3 answers

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

 import json data = json.dumps({'a': 1}) 
+14
source
 from django.utils import simplejson data = simplejson.dumps({'a': 1}) 
+6
source

Libraries like json or simplejson are not very cool for 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
source

Source: https://habr.com/ru/post/1312385/


All Articles