Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Conversion of Object to String function code (json str) in javascript


May 08, 2021 JSON



This article describes how to convert Object into a String function in JavaScript, as detailed in the following code:

The code is as follows:

function obj2str(o){ 
var r = []; 
if(typeof o =="string") return "\""+o.replace(/([\'\"\\])/g,"\\$1").replace(/(\n)/g,"\\n").replace(/(\r)/g,"\\r").replace(/(\t)/g,"\\t")+"\""; 
if(typeof o == "object"){ 
if(!o.sort){ 
for(var i in o) 
r.push(i+":"+obj2str(o[i])); 
if(!!document.all && !/^\n?function\s*toString\(\)\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/.test(o.toString)){ 
r.push("toString:"+o.toString.toString()); 
} 
r="{"+r.join()+"}" 
}else{ 
for(var i =0;i<o.length;i++) 
r.push(obj2str(o[i])) 
r="["+r.join()+"]" 
} 
return r; 
} 
return o.toString(); 
} 

Turn the object into a string with the native JSON object

[javascript]
  1. var jsObj = {};
  2. jsObj.testArray = [1,2,3,4,5];
  3. jsObj.name = 'CSS3' ;
  4. jsObj.date = '8 May, 2011' ;
  5. var str = JSON.stringify(jsObj);
  6. alert(str);

Change from a JSON string to an object
[javascript]
  1. var jsObj = {};
  2. jsObj.testArray = [1,2,3,4,5];
  3. jsObj.name = 'CSS3' ;
  4. jsObj.date = '8 May, 2011' ;
  5. var str = JSON.stringify(jsObj);
  6. var str1 = JSON.parse(str);
  7. alert(str1);