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);
}