关于javascript:将数组转换为JSON

converting array to JSON

本问题已经有最佳答案,请猛点这里访问。

所以我有一个像这样的数组

1
2
3
4
5
6
var me =[
{'we':'me','see':'tree','lee':'bee'},
{'we':'me','see':'tree','lee':'bee'},
{'we':'me','see':'tree','lee':'bee'},
{'we':'me','see':'tree','lee':'bee'}
];

如何将其转换为以""开头、以""结尾的JSON对象


JSON.stringify一起?

1
2
3
4
5
6
7
8
9
10
11
12
var me =[
    {'we':'me','see':'tree','lee':'bee'},
    {'we':'me','see':'tree','lee':'bee'},
    {'we':'me','see':'tree','lee':'bee'},
    {'we':'me','see':'tree','lee':'bee'}
];

console.log(JSON.stringify(me));    // returns whole JSON.
console.log(JSON.stringify(me[0])); // returns what you want, 'starting with {}'.

//    if you want to start with {} with all data:
console.log(JSON.stringify({me:me}));


这样地:

1
2
3
4
JSON.stringify(me.reduce(function(o, v, i) {
    o[i] = v;
    return o;
}, {}));


1
var myJsonString = JSON.stringify(me);

更新的

1
2
3
4
5
6
7
8
9
10
11
12
var me =[
{'we':'me','see':'tree','lee':'bee'},
{'we':'me','see':'tree','lee':'bee'},
{'we':'me','see':'tree','lee':'bee'},
{'we':'me','see':'tree','lee':'bee'}
];


var myjson={'list':""}
myjson.list=me;
var myJsonString = JSON.stringify(myjson);
console.log(myJsonString);