-8

当我打电话时JSON.stringify,我得到一个 JSON 字符串,如[{"id":"001","name":"Mary"},{"id":"002","name": "Tom"}]. 我怎样才能使它看起来像这样?

[
    {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"}
]
4

1 回答 1

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}';
    }
}
于 2012-09-11T00:32:30.817 回答