Reputation: 1413
This one has had me pulling out my hair. I've been trying to deserialize JSON in Django for the last couple 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 the 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 it hasn't been working. I know this is probably a really trivial question, but I've never used JSON before, and I'd really appreciate some help. Thanks!
Upvotes: 9
Views: 30575
Reputation: 3467
from django.core import serializers
obj_generator = serializers.json.Deserializer(request.POST['data'])
for obj in obj_generator:
obj.save()
Upvotes: 5
Reputation: 599610
serializers.deserialize
is for deserializing a particular type of JSON - that is, data that was serialized from model instances using serializers.serialize
. For your data, you just want the standard simplejson
module.
And the second thing wrong is that your response isn't 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'])
Upvotes: 19