如何从 JSON 数组 JavaScript 获取数据

How to get data from JSON array JavaScript

我想从 piedatalist 中推送数据,它包含两个属性,value 和 key,我想像这样 [key,value] 传递给 jqplot 来渲染图表,但是它不起作用。

$(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);
});

开头的JSON不能直接粘贴到代码中。它是一个字符串,但有换行符会打断字符串,双引号字符也会结束字符串。

您可以将 JSON 作为变量而不是字符串粘贴进去,JavaScript 就可以了:

var json = [{"pieDataList": 
             [{"value":100,"key":"non"}],

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