Django: Reading Array Of Json Objects From Querydict
Solution 1:
You should stringify your JSON using JSON.stringify(). This will convert the JSON Object into string format so it can be parsed correctly on the other end. On the other end you will need to use json.loads() to "unstringify" the object.
javascript:
var test = [{"id": 1},{"id": 2},{"id": 3}];
$.post(
"/insert_tc",
{
json_data: JSON.stringify(test),
"type": 'clone',
"csrfmiddlewaretoken": $csrf_token
},
function(json) {
//CALLBACK
},
"json"
);
View:
import json
definsert_tc(request):
if request.method == 'POST':
ret = request.POST
type = ret['type']
list = json.loads(ret['json_data'])
Solution 2:
This is actually jQuery, not Django, being strange. Your test
variable does not contain JSON, but actual JS objects. jQuery, for reasons best known to itself, parses this into some very weird format before posting, hence the result you get. If you did this instead (note the quotes around the whole thing):
var test = '[{"id": 1},{"id": 2},{"id": 3}]';
you'd find you get very nearly the QueryDict you expect: the only thing you then need to do is to call json.loads(ret['json_data'])
.
Also for reasons that I can't understand. jQuery doesn't contain any functionality to convert your array of objects to JSON. You'll need to find a plugin or separate library for that.
Post a Comment for "Django: Reading Array Of Json Objects From Querydict"