[英]How to extract specific properties from each JSON object using javascript
我有一個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小提琴 :
預期的結果是這樣的[“道路”,2.2]然后我想把它作為循環運行數據內的所有國家,以獲得類似的數組
您忘記將json字符串解析為JSONObject,因此您無法從字符串訪問key
屬性。
在var data = JSON.stringify(countriesByName);
你必須像這樣解析你的對象:
var data = JSON.parse(data);
完成此操作后,您可以訪問JSONObject屬性。
檢查這個演示 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.