将JavaScript数组转换为JSON [duplicate]

c9qzyr3d  于 2023-02-01  发布在  Java
关注(0)|答案(3)|浏览(191)
    • 此问题在此处已有答案**:

(23个答案)
八年前就关门了。
所以我有一个数组,看起来像这样:

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对象

5hcedyr0

5hcedyr01#

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

iqjalb3h2#

就像这样:

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

jjjwad0x3#

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

相关问题