JSON Format

2015-01-12 11:35  915人阅读  评论 (0)

叨叨

遇到这个问题 也懒得自己写了 就去github上无耻的剽窃了一段 地址:https://github.com/phoboslab/json-format

格式化函数

function JSONFormat(json) {
    var p = [],
        push = function( m ) { return '\\' + p.push( m ) + '\\'; },
        pop = function( m, i ) { return p[i-1] },
        tabs = function( count ) { return new Array( count + 1 ).join( '\t' ); };

    p = [];
    var out = "",
        indent = 0;

    // Extract backslashes and strings
    json = json
        .replace( /\\./g, push )
        .replace( /(".*?"|'.*?')/g, push )
        .replace( /\s+/, '' );      

    // Indent and insert newlines
    for( var i = 0; i < json.length; i++ ) {
        var c = json.charAt(i);

        switch(c) {
            case '{':
            case '[':
                out += c + "\n" + tabs(++indent);
                break;
            case '}':
            case ']':
                out += "\n" + tabs(--indent) + c;
                break;
            case ',':
                out += ",\n" + tabs(indent);
                break;
            case ':':
                out += ": ";
                break;
            default:
                out += c;
                break;      
        }                   
    }

    // Strip whitespace from numeric arrays and put backslashes 
    // and strings back in
    out = out
        .replace( /\[[\d,\s]+?\]/g, function(m){ return m.replace(/\s/g,''); } )
        .replace( /\\(\d+)\\/g, pop ) // strings
        .replace( /\\(\d+)\\/g, pop ); // backslashes in strings

    return out;
};