我有一个 json 信息,我想用它来创建一个像这样的对象:
var legends = {
"Altimetry" : {
0 : {
legenrowname : "0m - 250m ",
fillcolor : "005500",
bordercolor : ""
},
1 : {
legenrowname : "250m - 1000m ",
fillcolor : "ffff7f",
bordercolor : ""
},
2 : {
legenrowname : "1000m - 5000m ",
fillcolor : "B47811",
bordercolor : ""
},
3 : {
legenrowname : "+ 5000m ",
fillcolor : "482400",
bordercolor : ""
}
}
};
alert(legends); //the result is this:
Object []
它被识别为一个对象(这是我下一步需要的)
现在,我正在尝试使用 legend2 动态创建它
var dataL = ${dataJsonLegends};
var legends2 ="";
var lengthL = dataL.length;
$.each(dataL, function(i, item){
legendName = item.legendname;
legends2= '"' + legendName + '":{';
dataR = item.rows;
var lengthR = dataR.length;
$.each(dataR, function(j, item2){
id=item2.uid;
rowname=item2.legendrowname;
fillcolor=item2.fillcolor;
rowobject = id + ' : { legenrowname:"' + rowname + '", fillcolor:"' + fillcolor + '"}';
if(j!=lengthR-1) rowobject = rowobject + ",";
legends2= legends2+ rowobject;
});
legends2= legends2+ '}';
if(i!=lengthL-1) legends2= legends2+ ",";
});
alert(legends2); //the result is this:
"Altimetry" : { 0 : { legenrowname : "0m - 250m ",
fillcolor : "005500",
bordercolor : ""
},1 : {
legenrowname : "250m - 1000m ",
fillcolor : "ffff7f",
bordercolor : ""
},2 : {
legenrowname : "1000m - 5000m ",
fillcolor : "B47811",
bordercolor : ""
},3 : {
legenrowname : "+ 5000m ",
fillcolor : "482400",
bordercolor : ""
}}
legends2 值是我所期望的,但我希望它被识别为一个对象,而不是一个具有对象结构的字符串。
我尝试了很多方法来解决它。JSON.parse
, eval
, 等等...但没有人工作。
¿ 有人可以帮我或给我小费吗?
编辑:传入的json
我发布了我的 json 对象 (dataL),我用它来创建我需要的结构。
[{"uid":1,"legendname":"Altimetry","legend_description":null,"rows":[{"uid":2,"legendrowname":"250m - 1000m","fillcolor":"ffff7f","bordercolor":null,"rast_value":null,"fillcolorrgb":null,"bordercolorrgb":null,"legendrow_description":null,"legend":null},{"uid":4,"legendrowname":"+ 5000m","fillcolor":"482400","bordercolor":null,"rast_value":null,"fillcolorrgb":null,"bordercolorrgb":null,"legendrow_description":null,"legend":null},{"uid":1,"legendrowname":"0m - 250m","fillcolor":"005500","bordercolor":null,"rast_value":null,"fillcolorrgb":null,"bordercolorrgb":null,"legendrow_description":null,"legend":null},{"uid":3,"legendrowname":"1000m - 5000m","fillcolor":"B47811","bordercolor":null,"rast_value":null,"fillcolorrgb":null,"bordercolorrgb":null,"legendrow_description":null,"legend":null}],"layer":{"id":1,"description":"Altimetry","geoserver":"/geoserver/Sopcawind/wms","name":"Sopcawind:srtm","transparent":true,"format":"image/png","viewparams":"","isbaselayer":false,"opacity":0.5,"color":"#2b383b","visibility":false,"groupid":1,"infocontrol":true,"geometry":"","featuretype":"","srs":"","extradata":"","legends":null,"project":null}}];
Edited2:我尝试使用代码,但我真的不需要 json 对象。我使用一个 json 对象来创建另一个具有这种结构的基本对象:
//loop legends
legends={"legendname": {
//loop rows
row.id : {
legenrowname : row.legendrowname,
fillcolor : row.fillcolor,
bordercolor : row.bordercolor
}
}}