设为首页收藏本站

就爱编程论坛

 找回密码
 注册

人人连接登陆

无需注册,直接登录

用新浪微博连接

一步搞定

QQ登录

只需一步,快速开始

查看: 426|回复: 1
打印 上一主题 下一主题

Json对象转普通字符串 [复制链接]

Rank: 9Rank: 9Rank: 9

  • TA的每日心情
    无聊
    2025-5-27 03:37:20
  • 签到天数: 366 天

    [LV.9]以坛为家II

    论坛先锋 学习至圣 荣誉成员 论坛元老 活跃之星 终极领袖

    我玩的应用:

    跳转到指定楼层
    楼主
    发表于 2011-7-5 17:23:32 |只看该作者 |正序浏览
    <script>
    Object.prototype.deep_clone = function()
    {
        eval("var tmp = " + this.toJSON());
        return tmp;
    }
    Object.prototype.toJSON = function()
    {
        var json = [];
        for (var i in this)
        {
            if (!this.hasOwnProperty(i)) continue;
            //if(typeof this == "function") continue;  
            json.push(
                i.toJSON() + " : " +
                ((this != null) ? this.toJSON() : "null")
            )
        }
        return "{\n " + json.join(",\n ") + "\n}";
    }
    Array.prototype.toJSON = function()
    {
        for (var i = 0, json = []; i < this.length; i++)
            json = (this != null) ? this.toJSON() : "null";
        return "[" + json.join(", ") + "]"
    }
    String.prototype.toJSON = function()
    {
        return '"' +
            this.replace(/(\\|\")/g, "\\$1")
            .replace(/\n|\r|\t/g, function()
            {
                var a = arguments[0];
                return (a == '\n') ? '\\n' :
                        (a == '\r') ? '\\r' :
                        (a == '\t') ? '\\t' : ""
            }) +
            '"'
    }
    Boolean.prototype.toJSON = function() { return this }
    Function.prototype.toJSON = function() { return this }
    Number.prototype.toJSON = function() { return this }
    RegExp.prototype.toJSON = function() { return this }
    // strict but slow  
    String.prototype.toJSON = function()
    {
        var tmp = this.split("");
        for (var i = 0; i < tmp.length; i++)
        {
            var c = tmp;
            (c >= ' ') ?
                (c == '\\') ? (tmp = '\\\\') :
                (c == '"') ? (tmp = '\\"') : 0 :
            (tmp =
                (c == '\n') ? '\\n' :
                (c == '\r') ? '\\r' :
                (c == '\t') ? '\\t' :
                (c == '\b') ? '\\b' :
                (c == '\f') ? '\\f' :
                (c = c.charCodeAt(), (' \\u00' + ((c > 15) ? 1 : 0) + (c % 16)))
            )
        }
        return '"' + tmp.join("") + '"';
    }
    //--------------------------
    var a = { a: "aaa", b: "bbb", c: 123 };
    var s = a.toJSON();
    alert(s);
    //-------------------------------------------
    </script>
    分享到: QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
    分享分享0 收藏收藏0 支持支持0 反对反对0 分享到人人 转发到微博
    [img=http://mail.qq.com/cgi-bin/qm_share?t=qm_mailme&email=fRUcHhYWGAQ9GxIFEBwUEVMeEhA]http://rescdn.qqmail.com/zh_CN/htmledition/images/function/qm_open/ico_mailme_02.png[/img]

    使用道具 举报

    Rank: 9Rank: 9Rank: 9

  • TA的每日心情
    无聊
    2025-5-27 03:37:20
  • 签到天数: 366 天

    [LV.9]以坛为家II

    论坛先锋 学习至圣 荣誉成员 论坛元老 活跃之星 终极领袖

    沙发
    发表于 2011-7-5 17:24:55 |只看该作者
    在网上看到一个很经典的类:

    <script type="text/javascript">

    var JSON = function(sJSON){
        this.objType = (typeof sJSON);
        this.self = [];
        (function(s,o){for(var i in o){o.hasOwnProperty(i)&&(s[i]=o[i],s.self[i]=o[i])};})(this,(this.objType=='string')?eval('0,'+sJSON):sJSON);
    }
    JSON.prototype = {
        toString:function(){
            return this.getString();
        },
        valueOf:function(){
            return this.getString();
        },
        getString:function(){
            var sA = [];
            (function(o){
                var oo = null;
                sA.push('{');
                for(var i in o){
                    if(o.hasOwnProperty(i) && i!='prototype'){
                        oo = o[i];
                        if(oo instanceof Array){
                            sA.push(i+':[');
                            for(var b in oo){
                                if(oo.hasOwnProperty(b) && b!='prototype'){
                                    sA.push(oo[b]+',');
                                    if(typeof oo[b]=='object') arguments.callee(oo[b]);
                                }
                            }
                            sA.push('],');
                            continue;
                        }else{
                            sA.push(i+':'+oo+',');
                        }
                        if(typeof oo=='object') arguments.callee(oo);
                    }
                }
                sA.push('},');
            })(this.self);
            return sA.slice(0).join('').replace(/\[object object\],/ig,'').replace(/,\}/g,'}').replace(/,\]/g,']').slice(0,-1);
        },
        push:function(sName,sValue){
            this.self[sName] = sValue;
            this[sName] = sValue;
        }
    }
    ===========================

    可以把里面的转换方法拿出来用:
    function getJsonString(jsonObj){
            var sA = [];
            (function(o){
                var oo = null;
                sA.push('{');
                for(var i in o){
                    if(o.hasOwnProperty(i) && i!='prototype'){
                        oo = o[i];
                        if(oo instanceof Array){
                            sA.push(i+':[');
                            for(var b in oo){
                                if(oo.hasOwnProperty(b) && b!='prototype'){
                                   sA.push(oo[b]+',');//感觉此处似乎没有必要加上,因为有这句所有最后需要replace(/\[object object\],/ig,'')
                                    if(typeof oo[b]=='object') arguments.callee(oo[b]);
                                }
                            }
                            sA.push('],');
                            continue;
                        }else{
                            if(typeof oo=='number')sA.push(i+':'+oo+',');
                            else sA.push(i+":'"+oo+"',");
                        }
                        if(typeof oo=='object') arguments.callee(oo);
                    }
                }
                sA.push('},');
            })(jsonObj);
            return sA.slice(0).join('').replace(/\[object object\],/ig,'').replace(/,\}/g,'}').replace(/,\]/g,']').slice(0,-1);
        }

    这经过验证是有效的,无论是复杂的还是简单的json对象。push方法里面this.self[sName] = sValue;
            this[sName] = sValue;
    为什么要做2次,保存了2个对象?红色标记部分是对原js进行的修改,非number类型的还是需要加上引号。这种方法不能处理数组型的json数据,比如:[{},{}]这种形式的,受此启发,下面的方法则可以处理这种情况。

    function getJsonString(jsonObj){
    var sA = [];
    (function(o){
       var isObj=true;
       if(o instanceof Array)
          isObj=false;
       else if(typeof o!='object'){
          if(typeof o=='string')
              sA.push('"'+o+'"');
          else
              sA.push(o);
          return;
       }
       sA.push(isObj?"{":"[");
       for(var i in o){
        if(o.hasOwnProperty(i) && i!='prototype'){
         if(isObj)
          sA.push(i+':');
           arguments.callee(o[i]);
           sA.push(',');   
        }
       }
       sA.push(isObj?"}":"]");
    })(jsonObj);
    return sA.slice(0).join('').replace(/,\}/g,'}').replace(/,\]/g,']');
    }

    下面还有一种方法:

    var J = {
    StrToJSON: function(str) {
    var a;
    eval('a=' + str + ';');
    return a;
    },
    JsonToStr: function(obj) {
    switch(typeof(obj))
    {
    case 'object':
    var ret = [];
    if (obj instanceof Array)
    {
    for (var i = 0, len = obj.length; i < len; i++)
    {
    ret.push(J.JsonToStr(obj[i]));
    }
    return '[' + ret.join(',') + ']';
    }
    else if (obj instanceof RegExp)
    {
    return obj.toString();
    }
    else
    {
    for (var a in obj)
    {
    ret.push(a + ':' + J.JsonToStr(obj[a]));
    }
    return '{' + ret.join(',') + '}';
    }
    case 'function':
    return 'function() {}';
    case 'number':
    return obj.toString();
    case 'string':
    return "\"" + obj.replace(/(\\|\")/g, "\\$1").replace(/\n|\r|\t/g, function(a) {return ("\n"==a)?"\\n":("\r"==a)?"\\r":("\t"==a)?"\\t":"";}) + "\"";
    case 'boolean':
    return obj.toString();
    default:
    return obj.toString();

    }
    }
    };

    比如:

    jsonObj = J.StrToJSON(jsonStr);

    这个没有进行验证,用到了正则。

    =============再一种,未验证========

    代码:
    Object.prototype.deep_clone = function(){
    eval("var tmp = " + this.toJSON());
    return tmp;
    }
    Object.prototype.toJSON = function(){
    var json = [];
    for(var i in this){
    if(!this.hasOwnProperty(i)) continue;
    //if(typeof this[i] == "function") continue;
    json.push(
    i.toJSON() + " : " +
    ((this[i] != null) ? this[i].toJSON() : "null")
    )
    }
    return "{\n " + json.join(",\n ") + "\n}";
    }
    Array.prototype.toJSON = function(){
    for(var i=0,json=[];i<this.length;i++)
    json[i] = (this[i] != null) ? this[i].toJSON() : "null";
    return "["+json.join(", ")+"]"
    }

    String.prototype.toJSON = function(){
    return '"' +
    this.replace(/(\\|\")/g,"\\$1")
    .replace(/\n|\r|\t/g,function(){
    var a = arguments[0];
    return (a == '\n') ? '\\n':
    (a == '\r') ? '\\r':
    (a == '\t') ? '\\t': ""
    }) +
    '"'
    }
    Boolean.prototype.toJSON = function(){return this}
    Function.prototype.toJSON = function(){return this}
    Number.prototype.toJSON = function(){return this}
    RegExp.prototype.toJSON = function(){return this}

    // strict but slow
    String.prototype.toJSON = function(){
    var tmp = this.split("");
    for(var i=0;i<tmp.length;i++){
    var c = tmp[i];
    (c >= ' ') ?
    (c == '\\') ? (tmp[i] = '\\\\'):
    (c == '"') ? (tmp[i] = '\\"' ): 0 :
    (tmp[i] =  
    (c == '\n') ? '\\n' :
    (c == '\r') ? '\\r' :
    (c == '\t') ? '\\t' :
    (c == '\b') ? '\\b' :
    (c == '\f') ? '\\f' :
    (c = c.charCodeAt(),('\\u00' + ((c>15)?1:0)+(c%16)))
    )
    }
    return '"' + tmp.join("") + '"';
    }

    测试:

    var json = {
    str : "abcde",
    num : 6,
    reg : /foobar/i,
    array : [1,2,3,4,5],
    func : function(x,y){return x+y},
    obj : {a : "b"}
    }.toJSON();

    alert(json);
    // result
    {
    "str" : "abcde",
    "num" : 6,
    "reg" : /foobar/i,
    "array" : [1, 2, 3, 4, 5],
    "func" : function(x,y){return x+y},
    "obj" : {
    "a" : "b"
    }
    }
    [img=http://mail.qq.com/cgi-bin/qm_share?t=qm_mailme&email=fRUcHhYWGAQ9GxIFEBwUEVMeEhA]http://rescdn.qqmail.com/zh_CN/htmledition/images/function/qm_open/ico_mailme_02.png[/img]

    使用道具 举报

    您需要登录后才可以回帖 登录 | 注册 人人连接登陆

    晴云孤魂's Blog|就爱编程搜帖|手机版|Archiver|就爱编程论坛     

    GMT+8, 2025-7-3 18:44 , Processed in 0.108833 second(s), 28 queries .

    Powered by Discuz! X2

    © 2001-2011 Comsenz Inc.

    回顶部