json字符串
[
{
"name":"2015年",
"statTotal":[
{
"total":"123",
"statType":"事件等級"
},
{
"total":"456",
"statType":"行政區(qū)域"
}
]
},
{
"name":"2016年",
"statTotal":[
{
"total":"789",
"statType":"事件等級"
},
{
"total":"110",
"statType":"行政區(qū)域"
}
]
},
{
"name":"2017年",
"statTotal":[
{
"total":"128",
"statType":"事件等級"
},
{
"total":"654",
"statType":"行政區(qū)域"
}
]
}]
問題
我在后臺獲取到這么一個json字符串,在前臺通過js做處理,需要將他在前臺解析成一個類型
下面的map集合,這里的statType的值是動態(tài)變化的:
["事件等級" : "123,789,128","行政區(qū)域":"456,110,654"]
自己的寫法
var legend = [];//圖例
var result = eval('(' + data + ')');//json字符串
var levelTotal = [];//存放事件級別統(tǒng)計值
var gridTotal = [];//存放區(qū)域...
var timeTotal = [];//...
var typeTotal = [];//...
var resultTotal = [];//...
var map = new Map();
for(var j = 0; j < (result[0].statTotal).length; j++){
legend.push((result[0].statTotal)[j].statType);
}
for (var i = 0; i < result.length; i++) {
for(var j = 0; j < (result[i].statTotal).length; j++){
if(result[i].statTotal[j].statType == "事件等級"){
levelTotal.push(result[i].statTotal[j].total);
}
if(result[i].statTotal[j].statType == "行政區(qū)域"){
gridTotal.push(result[i].statTotal[j].total);
}
if(result[i].statTotal[j].statType == "事件類型"){
typeTotal.push(result[i].statTotal[j].total);
}
if(result[i].statTotal[j].statType == "事件后果"){
resultTotal.push(result[i].statTotal[j].total);
}
if(result[i].statTotal[j].statType == "時間"){
timeTotal.push(result[i].statTotal[j].total);
}
}
}
//構(gòu)建map鍵值對
for(var i = 0 ; i<legend.length ; i++){
if(legend[i] == "事件等級"){
map.set(legend[i],levelTotal);
}
if(legend[i] == "行政區(qū)域"){
map.set(legend[i],gridTotal);
}
if(legend[i] == "事件類型"){
map.set(legend[i],typeTotal);
}
if(legend[i] == "事件后果"){
map.set(legend[i],resultTotal);
}
if(legend[i] == "時間"){
map.set(legend[i],timeTotal);
}
}
我自己的寫法不正確,因?yàn)閟tatType的值是動態(tài)變化的,而我自己的是寫死的,然后if判斷,
還希望各位前輩們能指點(diǎn)一二,小弟在此謝過!
關(guān)于一個json字符串的解析問題
慕村225694
2018-12-06 11:31:49