我有一个java地图,我将其转换为json。这就是我的脚本的样子
var newVar = '[';
for(var x in pdict.Stores){
newVar += '{' + '"Store_ID":"' + x.ID + '",';
newVar += '"inv list id":"' + x.inventoryList.ID + '",';
newVar += '"Store Address":"' + x.address1 + '",';
newVar += '"zip":"' + x.postalCode + '"},';
}
newVar += ']';
pdict.Stores正在给我一张地图。在进行连接时,最后一个逗号被添加到json的末尾,json变得无效。如何在']'
关闭之前删除最后一个','这是输出
[{"Store_ID":"46305","inv list id":"jonesny-46305-inventory","Store Address":"739 Reading Avenue Suite #306","zip":"19610"},{"Store_ID":"48760","inv list id":"jonesny-46305-inventory","Store Address":"1665 State Hill Rd","zip":"19610"},{"Store_ID":"48811","inv list id":"jonesny-46305-inventory","Store Address":"1665 State Hill Road","zip":"19601"},{"Store_ID":"53046","inv list id":"jonesny-46305-inventory","Store Address":"2630 Westview Dr","zip":"19610"},]
我不能使用jquery。它必须是基于javascript的解决方案。
答案 0 :(得分:3)
不要这样做。
创建一个新对象,将其构建出来,并使用stringify
将其序列化。
var a = [];
for(var x in pdict.Stores){
var b = {};
b.Store_ID = x.id;
b["inv list id"] = x.inventoryList.ID;
b["Store Address"] = x.address1;
b.zip = x.postalCode;
a.push(b);
}
return JSON.stringify(a);