javascripthtmlarraysjqplot

How to get data from JSON array JavaScript


I want to push the data from piedatalist which contains two attributes, value and key and I want to pass to jqplot like this [key,value] to render the chart but it doesn't work.

$(document).ready(function () {
    var json = JSON.parse("[{"pieDataList":
        [{"value": 100, "key": "non"}],
        "titre": "fghjklcom", "nbreReponse": 1}, {
        "pieDataList": [{"value": 100, "key": "non"}],
        "titre": "fghjklcom", "nbreReponse": 1}]");
    // $.each(json, function (index,ch) {
    for (i in json) {
        var value = [];
        //get the map
        for (j = 0; j < json[i].PieDataList.length; j++) {
            //iterate each item of list
            value.push([json[i].PieDataList[j].key,
                json[i].PieDataList[j].value]);
        }
        var plot1 = jQuery.jqplot('ch', [value],
            {
                seriesDefaults: {
                    // Make this a pie chart.
                    renderer: jQuery.jqplot.PieRenderer,
                    rendererOptions: {
                        // Put data labels on the pie slices.
                        // By default, labels show the percentage of the
                        slice.
                        showDataLabels: true
                    }
                },
                legend: {show: true, location: 'e'}
            })
    }

    alert(item.PieDataList);
    console.log("Titre=" + item.Titre);
});

Solution

  • The JSON at the start can't just be pasted into the code. It's a string, but there are newlines which break strings, and double-quote characters which would end the string also.

    You can just paste in the JSON as a variable instead of a string and JavaScript will allow it just fine:

    var json = [{"pieDataList": 
                 [{"value":100,"key":"non"}],
    
     "titre":"fghjklcom","nbreReponse":1},{"pieDataList": 
    [{"value":100,"key":"non"}],
    "titre":"fghjklcom","nbreReponse":1}];