KiMoGiGi 技术文集

不在乎选择什么,而在乎坚持多久……

IT博客 首页 联系 聚合 管理
  185 Posts :: 14 Stories :: 48 Comments :: 0 Trackbacks
函数的主要功能是:传入一个Json对象(为了节省空间,一般请求返回的Json都是没有格式化的,可读性不好),可以输出格式化字符串,提高Json可读性。
虽然很多IDE或工具已经实现,但有时做简单测试时,格式化还是需要的。

假设,JS调用(假设界面有一个id为result的textarea)
var json = {
    Id: 
1,
    Name: 
"Test",
    Date: 
new Date(),
    Subjects:
    [
        {
            Name: 
"语文"
        },
        {
            Name: 
"数学"
        },
        {
            Name: 
"英语",
            Marks: [
9010083, { Test: "aaa"}]
        }
    ],
    Company:
    {
        Name: 
"Microsoft",
        Location: 
"USA"
    },
    Test: 
null
};
//-------------测试
//
格式化Json字符串
document.getElementById("result").value = JsonUti.convertToString(json);

界面输出


实现代码如下:
        var JsonUti = {
            
//定义换行符
            n: "\n",
            
//定义制表符
            t: "\t",
            
//转换String
            convertToString: function(obj) {
                
return JsonUti.__writeObj(obj, 1);
            },
            
//写对象
            __writeObj: function(obj    //对象
                    , level             //层次(基数为1)
                    , isInArray) {       //此对象是否在一个集合内
                //如果为空,直接输出null
                if (obj == null) {
                    
return "null";
                }
                
//为普通类型,直接输出值
                if (obj.constructor == Number || obj.constructor == Date || obj.constructor == String || obj.constructor == Boolean) {
                    
var v = obj.toString();
                    
var tab = isInArray ? JsonUti.__repeatStr(JsonUti.t, level - 1) : "";
                    
if (obj.constructor == String || obj.constructor == Date) {
                        
//时间格式化只是单纯输出字符串,而不是Date对象
                        return tab + ("\"" + v + "\"");
                    }
                    
else if (obj.constructor == Boolean) {
                        
return tab + v.toLowerCase();
                    }
                    
else {
                        
return tab + (v);
                    }
                }
 
                
//写Json对象,缓存字符串
                var currentObjStrings = [];
                
//遍历属性
                for (var name in obj) {
                    
var temp = [];
                    
//格式化Tab
                    var paddingTab = JsonUti.__repeatStr(JsonUti.t, level);
                    temp.push(paddingTab);
                    
//写出属性名
                    temp.push(name + " : ");
 
                    
var val = obj[name];
                    
if (val == null) {
                        temp.push(
"null");
                    }
                    
else {
                        
var c = val.constructor;
 
                        
if (c == Array) { //如果为集合,循环内部对象
                            temp.push(JsonUti.n + paddingTab + "[" + JsonUti.n);
                            
var levelUp = level + 2;    //层级+2
 
                            
var tempArrValue = [];      //集合元素相关字符串缓存片段
                            for (var i = 0; i < val.length; i++) {
                                
//递归写对象                         
                                tempArrValue.push(JsonUti.__writeObj(val[i], levelUp, true));
                            }
 
                            temp.push(tempArrValue.join(
"," + JsonUti.n));
                            temp.push(JsonUti.n 
+ paddingTab + "]");
                        }
                        
else if (c == Function) {
                            temp.push(
"[Function]");
                        }
                        
else {
                            
//递归写对象
                            temp.push(JsonUti.__writeObj(val, level + 1));
                        }
                    }
                    
//加入当前对象“属性”字符串
                    currentObjStrings.push(temp.join(""));
                }
                
return (level > 1 && !isInArray ? JsonUti.n : "")                       //如果Json对象是内部,就要换行格式化
                    + JsonUti.__repeatStr(JsonUti.t, level - 1+ "{" + JsonUti.n     //加层次Tab格式化
                    + currentObjStrings.join("," + JsonUti.n)                       //串联所有属性值
                    + JsonUti.n + JsonUti.__repeatStr(JsonUti.t, level - 1+ "}";   //封闭对象
            },
            __isArray: 
function(obj) {
                
if (obj) {
                    
return obj.constructor == Array;
                }
                
return false;
            },
            __repeatStr: 
function(str, times) {
                
var newStr = [];
                
if (times > 0) {
                    
for (var i = 0; i < times; i++) {
                        newStr.push(str);
                    }
                }
                
return newStr.join("");
            }
        };
 

实例下载:JsonToString.rar
posted on 2009-09-29 00:44 KiMoGiGi 阅读(5729) 评论(2)  编辑 收藏 引用 所属分类: JavaScriptWeb小技巧

评论

# re: 【原】Json对象格式化字符串输出 2014-02-14 20:49 在线工具
http://www.atool.org/jsonformat.php
json在线格式化~  回复  更多评论
  

# re: 【原】Json对象格式化字符串输出 2014-07-08 09:59 sss
{
"appid":wxc85cc3f6ad2ad16e,
"traceid":sanmuliu,
"package":bank_type=WX&body=IOSTest&fee_type=1&input_charset=UTF-8&notify_url=http%3A%2F%2Fpayment.t3.com.cn%2Fnotify%2Ftenpay&out_trade_no=1cdf14d1e3699d61d237cf76ce1c2dca&partner=1217702301&spbill_create_ip=error&total_fee=1&sign=20D651A4E130672E5CA17555925BA83D,
"timestamp":1404784169,
"app_signature":c7469da60f997392be6adb413c403169c5c0b6ac,
"sign_method":sha1,
}  回复  更多评论
  

只有注册用户登录后才能发表评论。