将数组转换为JSON

时间:2014-04-25 11:42:11

标签: javascript arrays json

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

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'}
];

如何将此转换为以' {'并以'}'

结尾

3 个答案:

答案 0 :(得分:3)

使用JSON.stringify

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)

像这样:

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

答案 2 :(得分:0)

var myJsonString = JSON.stringify(me);

<强>已更新

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);