如何可以轉換該:轉換Array對象爲JSON在Javascript
var expenseList = [[1,"Beverages"],
[2,"Condiments" ],
[3,"Confections" ],
[4,"Dairy Products" ],
[5,"Grains/Cereals" ],
[6,"Meat/Poultry" ],
[7,"Produce" ],
[8,"Seafood" ]];
成這樣:
output = [
{ value: 1, text: "Beverages" },
{ value: 2, text: "Condiments" },
{ value: 3, text: "Confections" },
{ value: 4, text: "Dairy Products" },
{ value: 5, text: "Grains/Cereals" },
{ value: 6, text: "Meat/Poultry" },
{ value: 7, text: "Produce" },
{ value: 8, text: "Seafood" }
];
第一數據源可以作爲輸入和第二是所需的輸出。 我試圖將數組轉換爲使用循環的字符串類型,然後將字符串解析爲json,但Json.pasre在那裏引發錯誤。
var list = '';
for (var i = 0; i < expenseList.length; i++) {
var showText = expenseList[i][1].replace('"', '\\"');
var key = expenseList[i][0];
list = '{ value: ' + key + ', text: "' + value + '"},' + list;
}
list = '[' + list.substr(0, list.length - 1) + ']';
var bindList;
bindList = JSON.parse(list);
試圖建立一個JSON對象作爲字符串是非常容易出錯。 – dan08
您所需的輸出中恰好有0(零)個「JSON對象」。或者任何與此有關的遠程JSON相關的東西。 –