欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JS对象序列化成json数据和json数据转化为JS对象的代码

程序员文章站 2022-09-08 20:38:25
js对象序列化成json数据: function serialize(obj){ switch(obj.constructor){ c...

js对象序列化成json数据:

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() + "\"";   
       break;     
   }   
 }   
var staff_list_obj  ={};  
var staff_id   = 1001;  
staff_list_obj[staff_id]  = {};  
staff_list_obj[staff_id]["姓名"] = '111';  
staff_list_obj[staff_id]["测试"] = '222';  
alert(serialize(staff_list_obj));

js对象序列化为json对象的方法二

var $ = $ || {};



/** 
 * 将js对象序列化为json字符串 
 * @param {mixed} o the variable to decode 
 * @return {string} the json string 
 * string json = $.encode(o); 
 */ 
$.encode = (function() {
  if ( typeof(json)!=='undefined' && typeof(json.stringify)!=='undefined') {
    return json.stringify;
  }
  var i = !!{}.hasownproperty, _ = function(i) {
    return i < 10 ? "0" + i : i;
  }, a = {
    "\b" : "\\b",
    "\t" : "\\t",
    "\n" : "\\n",
    "\f" : "\\f",
    "\r" : "\\r",
    "\"" : "\\\"",
    "\\" : "\\\\"
  };
  return (function(c) {
    if (typeof c == "undefined" || c === null) {
      return "null";
    } else {
      if (object.prototype.tostring.call(c) === "[object array]") {
        var b = ["["], g, e, d = c.length, f;
        for (e = 0; e < d; e += 1) {
          f = c[e];
          switch (typeof f) {
            case "undefined" :
            case "function" :
            case "unknown" :
              break;
            default :
              if (g) {
                b.push(",");
              }
              b.push(f === null ? "null" : $.encode(f));
              g = true;
          }
        }
        b.push("]");
        return b.join("");
      } else {
        if ((object.prototype.tostring.call(c) === "[object date]")) {
          return "\"" + c.getfullyear() + "-" + _(c.getmonth() + 1) + "-" + _(c.getdate()) + "t" + _(c.gethours()) + ":" + _(c.getminutes()) + ":" + _(c.getseconds()) + "\"";
        } else {
          if (typeof c == "string") {
            return "\"" + c.replace(/([\x00-\x1f\\"])/g, function(b, _) {
              var i = a[_];
              if (i) {
                return i;
              }
              return '';
            }).replace(/[^\u0000-\u00ff]/g, function($0) {
              return escape($0).replace(/(%u)(\w{4})/gi, "\\u$2")
            }) + "\"";
          } else {
            if (typeof c == "number") {
              return isfinite(c) ? string(c) : "null";
            } else {
              if (typeof c == "boolean") {
                return string(c);
              } else {
                b = ["{"], g, e, f;
                for (e in c) {
                  if (!i || c.hasownproperty(e)) {
                    f = c[e];
                    if (f === null) {
                      continue;
                    }
                    switch (typeof f) {
                      case "undefined" :
                      case "function" :
                      case "unknown" :
                        break;
                      default :
                        if (g) {
                          b.push(",");
                        }
                        b.push($.encode(e), ":", $.encode(f));
                        g = true;
                    }
                  }
                }
                b.push("}");
                return b.join("");
              }
            }
          }
        }
      }
    }
  });
})();

json数据转化为js对象:

var jsonstring={....}/[....];
eval("var obj="+jsonstring);
alert(obj);

写道

function evaljson(json){ 
var obj = null; 
try { 
obj = eval("(" + json + ")"); 
} catch(e){} 

return obj ; 
}