Method to convert a json object to a string

  • 2020-03-30 02:04:53
  • OfStack

 
 
tools.j2s = function(O) { 
var S = []; 
var J = ""; 
if (Object.prototype.toString.apply(O) === '[object Array]') { 
for ( var i = 0; i < O.length; i++) { 
S.push(this.j2s(O[i])); 
} 
J = '[' + S.join(',') + ']'; 
} else if (Object.prototype.toString.apply(O) === '[object Date]') { 
J = "new Date(" + O.getTime() + ")"; 
} else if (Object.prototype.toString.apply(O) === '[object RegExp]' || Object.prototype.toString.apply(O) === '[object Function]') { 
J = O.toString(); 
} else if (Object.prototype.toString.apply(O) === '[object Object]') { 
for ( var i in O) { 
var tempObj = ""; 
if(typeof (O[i]) == 'string') { 
tempObj = '"' + O[i] + '"'; 
} else if(typeof (O[i]) === 'object') { 
tempObj = this.j2s(O[i]); 
} else { 
tempObj = O[i]; 
} 
S.push('"' + i + '":' + tempObj); 
} 
J = '{' + S.join(',') + '}'; 
} else if (Object.prototype.toString.apply(O) === '[object String]') { 
J = '"' + O + '"'; 
} else { 
J = O; 
} 
return J; 
}; 
//Json strings are converted to json objects
tools.s2j = function(jsonString) { 
if(jsonString == null || jsonString == "" ) { 
jsonString = "{}"; 
} 
return eval('('+jsonString+')'); 
}; 


//JSON string to Object
tools.json2Obj = function(_json) { 
if (_json == '') { 
//Alert (" function initialization failed!" );
return ""; 
} 
return eval("({root:"+_json+"})"); 
}; 


Related articles: