javascript JSON.stringify()将数组放在同一行

时间:2017-07-13 19:04:24

标签: javascript json stringify

我正在使用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
  ]
}

任何建议都会很棒。

1 个答案:

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

文档:JSON.stringify()