Deserializing JSON in Django

This man made me pull my hair out. I have been trying to deserialize JSON in Django for the last couple of hours.

I have a function:

# in index.html function updateWidgetData(){ var items=[]; for statement here: for statement here: var item={ id: $j(this).attr('id'), collapsed: collapsed, order : i, column: columnId }; items.push(item); var sortorder={ items: items}; $j.post('2', 'data='+$j.toJSON(sortorder), function(response) { if(response=="success") $j("#console").html('<div class="success">Saved</div>').hide().fadeIn(1000); setTimeout(function(){ $j('#console').fadeOut(1000); }, 2000); }); } 

And I'm trying to deserialize JSON in django:

 # in views.py if request.is_ajax(): for item in serializers.deserialize("json", request.content): item = MyObject(id=id, collapsed=collapsed, order=order, column=column) return HttpResponse("success") else: .... 

And he did not work. I know this is probably a really trivial question, but I have never used JSON before, and I am very grateful for the help. Thanks!

+4
source share
2 answers

serializers.deserialize designed to deserialize a specific JSON type, that is, data that has been serialized from model instances using serializers.serialize . For your data, you need a standard simplejson module.

And secondly, it is not true that your answer is not just JSON - it is an HTTP POST with JSON in the data field. So:

 from django.utils import simplejson data = simplejson.loads(request.POST['data']) 
+13
source
 from django.core import serializers obj_generator = serializers.json.Deserializer(request.POST['data']) for obj in obj_generator: obj.save() 

Now the objects should be saved and visible in django admin

+2
source

All Articles