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!
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.
Deserialization is the process of reversing a String from a previously serialized format. This coverts the serialized String into a format that allows its Data Structure properties to be accessible to manipulation.
A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.
The default method of deserialization is json. loads() which takes a string as an input and outputs a JSON dictionary object. To convert the dictionary object to a custom class object, you need to write a deserialize method. The easiest way is to add a static method to the class itself.
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'])
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With