What is the best way to accept a nested json object in a django view ?
The request
$.ajax({
type: 'POST',
url: 'results/' + self.id + '/',
contentType:"application/json; charset=utf-8",
data: JSON.stringify(values),
dataType:"json",
...
values is a javascript dictionary object.
Object {Cart: Array[2], Di: "5"}
Cart: Array[2]
0: Object
N: 1
PR: 0.75
__proto__: Object
1: Object
N: "2"
PR: 2.5
__proto__: Object
length: 2
__proto__: Array[0]
Di: "5"
The view
def do_something(request,pid):
print json.loads(request.body)
This is the raw post data
{"Cart":["{\"PR\":4,\"N\":1}","{\"PR\":1.2,\"N\":\"2\"}"],"Di":"5"}
The problem is that json.loads leaves the inner dicts in the Cart array as unicode objects.
I've tried using jsonpickle and the old simplejson but i'm getting the same results.
This seem pretty basic - Is there a simple solution for this ?
EDIT
After reading your posts I understand it might be a client side issue but I'm still stringifying the json data only once in the ajax call.
This is how i generate values
The basic case - simple Dict
self.serialized_value = function() {
if (self.value()) {
var d = {}
d[self.name] = self.value();
return (d);
}
};
For object containing several parameters
self.get_serialized_values = function() {
var values = {};
$.map(self.parameters(), function(p) {
$.extend(values, p.serialized_value());
});
return values;
};
For object that contain other objects
self.serialized_value = function() {
var child_data = [];
$.each(self.items() , function(k,v) {
child_data.push(v.get_serialized_values());
});
var d = {}
d[self.name] = child_data;
return (d);
};
And finally, JSON.stringify is applied only in the ajax call
..
data: JSON.stringify(self.get_serialized_values())
..
Where in the code is the json being stringified twice ?
Cartlist consists of two strings that themselves need decoding. What in heavens name is producing this?