Is this JSON string valid and if so how to access nested items in Django view
I am trying to work through an issue where I am sending JSON from jQuery via Ajax().
In this function I create a nested array of objects, put the whole array through JSON.strigify() and then send it to my model in Django.
I successfully decode the JSON string (No errors) but I can not access it or any of its parts. Same happens if I convert to dict() or list(). Is the JSON I am sending to my view valid for working with it in Django or do I need to change how I construct it in order to access its values.
JQuery Constructing and sending array:
$(document).on('click','#exModel',function () {
const sending = [];
$("table tr").each(function () {
var p1 = $(this).find("th label").html();
var p2 = $(this).find("td input").attr('id');
var p3 = $(this).find("td input").val();
const build = {bnaa:p1,id:p2,vals:p3};
sending.push(build);
});
console.log(sending);
$.ajax({
url: '../coreqc/exModel/',
data: JSON.stringify({'sending':sending}),
type: 'POST',
headers: {'content_type':'application/json','X-CSRFToken': '{{ csrf_token }}'},
async: 'true',
success: function (data) {
console.log("I made it back")
//dom: 'Bfrtip',
}
});
});
The array is sent to my view in Django. In the browser console when I log it before send it looks like this:
[{bnaa: "Product 1:", id: "1", vals: ""}, {bnaa: "Product 2:", id: "2", vals: ""}, {bnaa: "Product 3:", id: "3", vals: ""}, {bnaa: "Product 4:", id: "4", vals: ""}, {bnaa: "Product 5:", id: "5", vals: ""}, {bnaa: "Product 6:", id: "6", vals: ""}, {bnaa: "Product 7:", id: "7", vals: ""}, {bnaa: "Product 8:", id: "8", vals: ""}, {bnaa: "Product 9:", id: "9", vals: ""}, {bnaa: "Product 10:", id: "10", vals: ""}]
When I decode this using json.loads() I then cannot unpack the values. I can print everything, if I turn it in to a dictionary I can display all items. I just can not get the keys and values.
@csrf_protect
def exModel(request):
data = request.body
data = json.loads(request.body)
print(data)
template = loader.get_template('coreqc/tester.html')
context = {
'data':data
}
return HttpResponse(template.render(context, request))
When I print data above I get the following in the terminal:
{'sending': [{'bnaa': 'Product 1:', 'id': '1', 'vals': ''}, {'bnaa': 'Product 2:', 'id': '2', 'vals': ''}, {'bnaa': 'Product 3:', 'id': '3', 'vals': ''}, {'bnaa': 'Product 4:', 'id': '4', 'vals': ''}, {'bnaa': 'Product 5:', 'id': '5', 'vals': ''}, {'bnaa': 'Product 6:', 'id': '6', 'vals': ''}, {'bnaa': 'Product 7:', 'id': '8', 'vals': ''}, {'bnaa': 'Product 9:', 'id': '8', 'vals': ''}, {'bnaa': 'Product 9:', 'id': '9', 'vals': ''}, {'bnaa': 'Product 10:', 'id': '10', 'vals': ''}]}
I have a tried every way I can to loop through the 'data' variable but, other than dumping the whole thing, can not access the nested items in 'sending' which is making me doubt the way its being sent.