代码改变世界

js对象序列化为json字符串

2008-11-25 10:10  snryang  阅读(4476)  评论(2编辑  收藏  举报

网上找了找将js对象序列化为json字符串的方法。结果都不近人意,最后自己写了一个。

注意你得自己为Date增加toString()方法。

function Serialize(obj){
    switch(obj.constructor){
        case Object:
            var str = "{";
            for(var o in obj){
                str += o + ":" + Serialize(obj[o]) +",";
            }
            if(str.substr(str.length-1) == ",")
                str = str.substr(0,str.length -1);
            return str + "}";
            break;
        case Array:            
            var str = "[";
            for(var o in obj){
                str += Serialize(obj[o]) +",";
            }
            if(str.substr(str.length-1) == ",")
                str = str.substr(0,str.length -1);
            return str + "]";
            break;
        case Boolean:
            return "\"" + obj.toString() + "\"";
            break;
        case Date:
            return "\"" + obj.toString() + "\"";
            break;
        case Function:
            break;
        case Number:
            return "\"" + obj.toString() + "\"";
            break; 
        case String:
            return "\"" + obj.toString().replace(/"/g,"\\\"") + "\"";
            break;    
    }
}