0

I'm trying to use Chart.js to generate a pie chart using dynamically generated data. I'm having trouble getting the data in the right format, I think I'm close but I've been stuck for a while.

I'm using ajax to get JSON data like this:

$.ajax({
    url: '../helpdesk/getTicketsPerSubcat/' + startDate + '/' + endDate + '/' + activeLabel,
    dataType: 'JSON',
    success: function(result){
        var pieData = new Array();

        // populate array
        for (i in result) {
            var foo = {value: result[i].total, label: result[i].subcategory}
            var jsonString = JSON.stringify(foo);
            pieData.push(jsonString);
        }
        console.log(pieData);
    }
});

Which returns:

["{"value":"2","label":"Disk Space"}", "{"value":"1","label":"Performance Issue"}"]

This is what the documentation says the data needs to look like:

var data = [
    {
        value: 300,
        label: "Red"
    },
    {
        value: 50,
        label: "Green"
    },
    {
        value: 100,
        label: "Yellow"
    }
]

I seem to have those extra quotes just inside the square brackets which must be what is causing an error (Uncaught TypeError: Cannot read property 'length' of undefined). Is JSON.stringify() the wrong function to be using? Any help would be very much appreciated!

1
  • Don't JSON.stringify the objects, and you should be good to go. Commented Aug 20, 2015 at 10:48

1 Answer 1

1

Is JSON.stringify() the wrong function to be using?

yes because a valid JSON is converted into a JSON string.

Instead just push the object you want to have in the array:

for (i in result) {
    var foo = {value: result[i].total, label: result[i].subcategory}
    pieData.push(foo);
}
Sign up to request clarification or add additional context in comments.

Comments

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.