当我调用JSON.stringify
时,我得到一个像[{"id":"001","name":"Mary"},{"id":"002","name":
"Tom"}]
这样的JSON字符串。我怎样才能使它看起来像这样?
[
{id: 7, name: "Ruby"},
{id: 29, name: "C#"},
{id: 31, name: "Fortran"},
{id: 37, name: "Visual Basic"},
{id: 41, name: "C"},
{id: 43, name: "C++"},
{id: 47, name: "Java"}
]
答案 0 :(得分:1)
好吧,显然你想要取出引号并将其缩进很好?然后我会事先做到这一点:
function indent(str) {
return str.replace(/\n/g, '\n\t');
}
function toPrettyObject(obj) {
var ajsoln = []; // Actual JavaScript Object Literal Notation
if(Object.prototype.toString.call(obj) === '[object Array]') {
for(var i = 0; i < obj.length; i++) {
ajsoln.push(indent(toPrettyObject(obj[i])));
}
return '[\n' + ajsoln.join(',\n') + '\n]';
} else if(typeof obj !== 'object') {
return JSON.stringify(obj);
} else {
for(var x in obj) {
ajsoln.push('\t' + (/^[a-zA-Z_\$][\w\$]+$/.test(x) ? x : JSON.stringify(x)) + ': ' + indent(toPrettyObject(obj[x])));
}
return '{\n' + ajsoln.join(',\n') + '\n}';
}
}