[英]javascript JSON.stringify() to put array on same line
我正在使用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
]
}
任何建议都很好。
您可以使用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));
此处的文档: JSON.stringify()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.