码迷,mamicode.com
首页 > 编程语言 > 详细

javascript JSON解析函数

时间:2015-09-04 16:52:56      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:

JSON=function(){
 return{
 encode:function(o){//编码JSON对象
   var str=‘‘;
   if(typeof(o.length)==‘number‘)
   {
    str=‘[‘;
    for(var i=0;i<o.length;i++)
    {
     if(o[i]==null)
      str+=‘null‘;
     else{
      var t=typeof(o[i]);
      switch(t){
      case ‘string‘:
       str+=‘"‘+o[i].replace(‘"‘,‘//"‘)+‘"‘;
       break;
      case ‘object‘:
       str+=this.encode(o[property]);
       break;
      case ‘number‘:
       str+=o[i];
       break;
      case ‘null‘:
       str+=property+‘:null,‘;break;
      case ‘function‘:
       str+=[i].toString();
       break;
      }
     }
     if(i<o.length-1)str+=‘,‘;
    }
    return str+‘]‘;
   }else{
    str=‘{‘;
    for(var property in o)
    {
     
     if(o[property]==null)
      str+=property+‘:null,‘;
     else
     {
      var t=typeof(o[property]);
      switch(t){
      case ‘string‘:
       str+=property+‘:"‘+o[property].replace(‘"‘,‘//"‘)+‘",‘;
       break;
      case ‘object‘:
       str+=property+":"+this.encode(o[property])+‘,‘;
       break;
      case ‘number‘:
       str+=property+":"+o[property]+‘,‘;
       break;
      case ‘function‘:
       str+=property+":"+o[property].toString()+‘,‘;
       break;
      }
     }
    }
   }
   if(str.length>0) return str.substr(0,str.length-1)+‘}‘;
   return str+‘}‘;
  },
 decode:function(str){//解析json文本
  try{
   return eval(‘(‘+str+‘)‘);
  }catch (e){
  }
   alert(‘error‘);
   return null;
  }
 }
}();

 

用法:

var obj=function(){
 return{
 ID:500,
 NAME:‘何正明‘,
 STATUS:‘online‘,
 SEX:null,
 ARRAY:[1,2],
 func:function(){
  return ‘aaa‘;
 }
 };
}();
function doparse(){
var newstr =JSON.encode(obj)
alert(newstr);
var newobj=JSON.decode(newstr);
alert(newobj.SEX);
}

javascript JSON解析函数

标签:

原文地址:http://www.cnblogs.com/lbnnbs/p/4781832.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!