这个json对象是通过ajax返回的。
[{"fiscal_year":2.012,"groupName":"Group1","Quantity":31666,"Revenue":"18,700,482.83"},
{"fiscal_year":2.013,"groupName":"Group1","Quantity":9264,"Revenue":"8003393.585"},
{"fiscal_year":2.014,"groupName":"Group1","Quantity":2483,"Revenue":"3,413,629.16"},
{"fiscal_year":2.012,"groupName":"Group2","Quantity":0,"Revenue":"3,055,922.45"},
{"fiscal_year":2.013,"groupName":"Group2","Quantity":0.00E+00,"Revenue":"3,916,824.84"},
{"fiscal_year":2.014,"groupName":"Group2","Quantity":0,"Revenue":"3,444,182.80"}
]
我需要修改它并将其保存为另一个json对象,以便我可以在列中显示年份。
$.ajax({
url: 'static/doc/sample.json',
type: 'GET',
dataType: 'JSON',
success: function(data){
var obj = [];
var business_group_nm = '';
$.each(data,function(key,value){
if(business_group_nm!=value.groupName){
obj.push({
"groupName": value.groupName,
"year":[value.fiscal_year:{
"Quantity":value.Quantity,
"Revenue":value.Revenue
}];
});
}else{
obj["year"].push(value.fiscal_year:{
"Quantity":value.Quantity,
"Revenue":value.Revenue
}];
});
}
business_group_nm = value.business_group_nm;
});
最终的json对象我希望它是:
[
{
"business_group_nm": "Group1",
"year": [
{
"2012": {
"Quantity": "31666",
"Revenue": "18,700,482.83"
}
},
{
"2013": {
"Quantity": "31666",
"Revenue": "18,700,482.83"
}
}
]
},
{
"business_group_nm": "Group2",
"year": [
{
"2012": {
"Quantity": "31666",
"Revenue": "18,700,482.83"
}
},
{
"2013": {
"Quantity": "31666",
"Revenue": "18,700,482.83"
}
}
]
},
];
但是我收到错误'Uncaught SyntaxError:Unexpected token:'
"year":[value.fiscal_year:{
"Quantity":value.Quantity,
"Revenue":value.Revenue
}];
由于
答案 0 :(得分:0)
obj["year"].push(value.fiscal_year:{
"Quantity":value.Quantity,
"Revenue":value.Revenue
}];
});
这没有任何意义,你不能在实际的对象表示法“外部”使用那种语法。使用.push
在这里也是错误的,这是一种Array方法,而不是对象。
以下行中的某些内容应该可以将新属性添加到obj["year"]
,使用fiscal_year值作为属性名称并将其指定为值:
obj["year"][value.fiscal_year] = {
"Quantity":value.Quantity,
"Revenue":value.Revenue
};
编辑:在这个地方,
"year":[value.fiscal_year:{
"Quantity":value.Quantity,
"Revenue":value.Revenue
}];
您使用的是方括号,表示数组,而不是对象 - 但数组没有任何此类“关联”键。如果你想将它作为一个对象,那么也可以在这里使用花括号。