如何使用javascript从每个JSON对象中提取特定属性

时间:2015-11-17 12:15:03

标签: javascript jquery arrays json

我有一个JSON数据集

[{"key":"Albania",
    "values":[{                                                                  
        "Country_Names":"Albania",
        "Total":"3.8",
        "Change_total":"-38.7",
        "Main activity electricity and heat production":"0.1",
        "Main activity electricity plants":"","Main activity CHP plants":"",
        "Unallocated autoproducers / Other energy industry own use":"0.1",
        "Other":"1.4",
        "Manufacturing industries and construction":"1",
        "Iron and steel":"0","Chemical and petrochemical":"0","Machinery":"",
        "Mining and quarrying":"",
        "Food and tobacco":"0.1",
        "Paper, pulp and printing":"",
        "Construction":"0",
        "Transport":"2.2",
        "Road":"2.2",
        "Domestic aviation":"",
        "Rail":"0",
        "Domestic navigation":"0.1",
        "Residential":"0.2",
        "Commercial and public services":"0",
        "Agriculture/forestry":"0.2",
        "Sub-bituminous coal / Lignite":"",
        "Other bituminous coal":"",
        "Natural gas":"0",
        "Motor gasoline excl. bio":"0.3",
        "Gas/diesel oil excl. bio":"2.2"
    }]
}]

我想从每个键(国家/地区)中提取特定值(例如Road,Rail),并从每个对象中绘制一个单独的饼图。例如,阿尔巴尼亚的一个图表显示了道路和铁路价值,然后是数据集中下一个国家的相同图表。

我正在尝试使用以下代码实现此目的:

function checkIt(data) {
    var countriesByName = d3.nest()
    .key(function(d) { return d.Country_Names; })
    .entries(data);
    //console.log(countriesByName)
    var data = JSON.stringify(countriesByName);
    console.log(data);
    function makePie() {
        function myfunc(data){
            var obj =  [];
            for (var i in data.key) {
                obj.push('Road' + m.countriesByName[i].key.values[i].Food+ ' and tobacco');
            }
        }
        var data1 =  myfunc(data);
        //console.log(data)
        var chart = c3.generate({
            bindto: "#left",
            data: {
                columns: [
                data1
                ],type : "donut" 
            }
        });
    }
    makePie();
};
d3.json("https://gist.githubusercontent.com/heenaI/cbbc5c5f49994f174376/raw/82cd19eff7db367193cf8ce00144a40ea8d140ac/data.json", checkIt);

我收到以下错误:

  

未捕获的TypeError:无法读取未定义的属性“0”

这是数据集的JS fiddle

预期的结果是这样的[“Road”,2.2]然后我想把它作为循环运行数据中的所有国家来获得类似的数组

1 个答案:

答案 0 :(得分:4)

您忘记将json字符串解析为JSONObject,因此您无法从字符串访问key属性。

var data = JSON.stringify(countriesByName);下,您必须像这样解析您的对象:

var data = JSON.parse(data);

完成此操作后,您可以访问JSONObject属性。

选中Demo