-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

Okay, so apparently you want to take out the quotes and indent it nicely? Then I would do that beforehand:

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 に答える