Reputation: 2200
Been struggling with this for hours now. Basically I need this json variable to become an array so that it can be recognised by Chart.js.
C# controller returns as follows:
return Json(new { DataString = json }, JsonRequestBehavior.AllowGet);
Backend returns the following string from json results:
[{value:228,color:"#B3A11A"},{value:255,color:"#948299"},{value:1,color:"#5108C5"},{value:271,color:"#A86199"},{value:246,color:"#6A8869"}]
Which is perfectly fine, but it doesn't want to "become" an array when I assign it to the 'array' variable, in this javascript:
for (var i = 0; i < tables.length; i++) {
$.get('/Stats/GetFieldJson', { fieldname: tables[i], tablename: @ViewData["tablename"]' },
function(data) {
var array = JSON.parse(data.DataString);
var ctx = $("#Maritalstatus").get(0).getContext("2d");
var myNewChart = new Chart(ctx);
new Chart(ctx).Pie(array, { scaleShowValues: true });
}, 'json');
}
How can I make data.DataString into a recognisable array that matches the array syntax of the controller's output?
Note If I simply say:
var array = [{value:228,color:"#B3A11A"},{value:255,color:"#948299"},{value:1,color:"#5108C5"},{value:271,color:"#A86199"},{value:246,color:"#6A8869"}]
it works perfectly.
Upvotes: 2
Views: 312
Reputation: 40739
I suspect the problem is that JSON.parse
is expecting well formed JSON, and in well formed JSON the keys need to be double quoted:
[{"value":228,"color":"#B3A11A"},{"value":255,"color":"#948299"},{"value":1,"color":"#5108C5"},{"value":271,"color":"#A86199"},{"value":246,"color":"#6A8869"}]
Upvotes: 3