我正在使用JSON.stringify
,我想知道是否有办法将数据保存在数组中的同一行。
我希望它看起来像这样:
"bob": {
"college": "UCLA",
"favorite_color": "green",
"favorite_numbers": [12, 42]
},
"fred": {
"college": "USC",
"favorite_color": "blue",
"favorite_numbers": [10, 16]
}
然而它出现了:
"bob": {
"college": "UCLA",
"favorite_color": "green",
"favorite_numbers": [
12,
42
]
},
"fred": {
"college": "USC",
"favorite_color": "blue",
"favorite_numbers": [
10,
16
]
}
任何建议都会很棒。
答案 0 :(得分:0)
您可以使用replacer
参数执行此操作:
var obj = {
"bob": {
"college": "UCLA",
"favorite_color": "green",
"favorite_numbers": [12, 42]
},
"fred": {
"college": "USC",
"favorite_color": "blue",
"favorite_numbers": [10, 16]
}
};
console.log('This is what you really want:');
console.log(JSON.stringify(obj, function(a, b) {
return (Object.prototype.toString.call(b) === '[object Array]') ? JSON.stringify(b) : b;
}, 4));
console.log('This is your result:');
console.log(JSON.stringify(obj, null, 4));