How to convert JavaScript object into LITERAL string? How to convert JavaScript object into LITERAL string? json json

How to convert JavaScript object into LITERAL string?


JavaScript has no built-in functions that will convert an object to a string representation of it which either:

  • Uses identifiers instead of strings for property names
  • Represents the original syntax used to create the object

You could write your own function for the former (at least when the property name can be represented as a literal) but the latter is impossible as JavaScript stores no information about the source code used to create the object in the first place.


You can do it with JSON.stringify and then with String.replace like follows:

var jsObj ={    abc: "hello",    bca: "allo",    cab: "dd:cc",    d: ["hello", "llo", "dd:cc"],    e: {abc: "hello", bca: "allo", cab: "dd:cc"}};function format(obj){    var str = JSON.stringify(obj, 0, 4),        arr = str.match(/".*?":/g);    for(var i = 0; i < arr.length; i++)        str = str.replace(arr[i], arr[i].replace(/"/g,''));    return str;}console.log(format(jsObj));