2

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.

2
  • 1
    in my opinion, your controller is not returning a string, it's returning a json array, so you don't need to parse it, i think Commented Mar 12, 2014 at 0:11
  • 1
    @أنيسب�?هاشم I thought so too at first, but then I saw the JSON format issue, which has bitten me before. Commented Mar 12, 2014 at 0:16

1 Answer 1

3

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"}]
5
  • Nope it's worked before without the quotation marks. Needs to be that way for chart.js to work. If I make it simply 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 Commented Mar 12, 2014 at 0:05
  • yes that works but if you use JSON.parse it has to be double quoted Commented Mar 12, 2014 at 0:13
  • Nevermind, tried it your way, worked, thank you very much (I'm a newb). Commented Mar 12, 2014 at 0:13
  • Try it: JSON.parse('[{k:1},{k:2}]') will throw an error about 'k' being unexpected Commented Mar 12, 2014 at 0:13
  • Yea got that v was unexpected. Works now. Commented Mar 12, 2014 at 0:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.