2010-08-12

從 AS3 改寫的 JavaScript JSON Formatter

參考 http://qops.blogspot.com/2010/04/json-formatter.html
用法
var jf = new JsonFormatter(JSON.stringify(response));
jQuery("#show1").html("<pre>" + jf.getResult() + "</pre>");



原始內容
/**
* ...
* @author shinder.lin
*/
function JsonFormatter(jsonString){
 this.jsonString = jsonString;
    this.spaces = 0;
    this.spaceUnit = "    ";
    this.resultStr = "";
    this.prevCh = "";
    
 // *** getResult method *** 
    this.getResult = function(){
  // alert("123");
  // alert(this.findBracket);
        if (this.jsonString) {
            this.findBracket(this.jsonString);
        }
        if (this.resultStr.charAt(0) == "\n") {
            this.resultStr = this.resultStr.slice(1);
        }
        return this.resultStr;
    };
 
 // *** findBracket method *** 
    this.findBracket = function(str){
        var ch;
        var leftStr;
        var midStr;
        var rightStr;
        for (var i = 0; i < str.length; i++) {
            ch = str.charAt(i);
            
            if (ch == '[' || ch == '{' || ch == ',') {
                leftStr = str.slice(0, i + 1);
                rightStr = str.slice(i + 1);
                break;
            }
            else 
                if (ch == '}' || ch == ']') {
                    leftStr = str.slice(0, i);
                    midStr = str.slice(i, i + 1);
                    rightStr = str.slice(i + 1);
                    break;
                }
        }
        if (leftStr == null) {
            return;
        }
        if (ch == ',' && (prevCh == '}' || prevCh == ']')) {
            this.resultStr += leftStr;
        }
        else {
            this.resultStr += this.getSpaces() + leftStr;
        }
        switch (ch) {
            case '[':
            case '{':
                this.spaces++;
                break;
            case '}':
            case ']':
                this.spaces--;
                break;
        }
        
        if (midStr != null) {
            this.resultStr += this.getSpaces() + midStr;
        }
        prevCh = ch;
        
        if (rightStr.length > 1) {
            this.findBracket(rightStr);
        }
        else {
            this.resultStr += "\n" + rightStr;
        }
    }
 
 // *** getSpaces method *** 
    this.getSpaces = function(){
        var str = "\n";
        for (var i = 0; i < this.spaces; i++) {
            str += this.spaceUnit;
        }
        return str;
    }
}

沒有留言:

FB 留言