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));
It does convert it to the literal syntax. You are able to create objects with multiple forms of syntax. Both of the following object declarations are valid:
var a = {a: "a"}var b = {"b": "b"}
If you want to remove the "" around the key you should be able to match them with the following regex /\"(.*?)\":/g and replace them with something like this:
function reformat(str) { var myRegexp = /\"(.*?)\":/g; match = myRegexp.exec(str); while (match != null) { str = str.replace(match[0], match[1] + ":"); match = myRegexp.exec(str); } return str;}
Hope that helps :)