Json=function () {
return{
Encode:function (o) {//Encode JSON object
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, ';
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) {//Parse JSON text
try{
Return eval (' (' +str+ ') ');
}catch (e) {
}
Alert (' Error ');
return null;
}
}
}();
Usage:
var obj=function () {
return{
ID:500,
NAME: ' He zhengming ',
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 parsing functions