hbms hbms - 19 days ago 5
Javascript Question

Javascript: Convert Object to String Recursively (including child objects and arrays) as if there were quotes around it

Over the past few months I've been trying various methods of converting an object into a string that perfectly represents the object input.

I've tried using JSON.stringify and re-formatting that, I've tried using other stackoverflow solutions, I also made my own attempt:

$ = Object.prototype; $['str'] = function ()
{
$u = Object.getOwnPropertyNames(this); $v = '{';
$i = 0; while ($i < $u.length)
{
$w = this[$u[$i]];
$x = ($b) => {return $b == toString.call($w).slice(8, -6)};
$y = $x('O') ? $w.str() : $x('A') ? JSON.stringify($w) : '"' + $w + '"';
$v += $u[$i] + ':' + $y + ','; ++$i;
};
return $v.slice(0, -1) + '}';
};


You Guessed it, it doesn't work. Please don't mark as duplicate, the other questions don't ask my exact question. I'm glad for any help.

EDIT: Added Input & Output

Input: {a: "x", b: ["y"], c: {d: ["z"]}, e: [{f: "g"}]} (Object)
Output: '{a: "x", b: ["y"], c: {d: ["z"]}, e: [{f: "g"}]}' (String)

Answer

You can try:

var obj = {a: "x", b: ["y"], c: {d: ["z"]}, e: [{f: "g"}]};

var objStr = JSON.stringify(obj).replace(/\"([^(\")"]+)\":/g,"$1:");

console.log(objStr);

Output:

{a:"x",b:["y"],c:{d:["z"]},e:[{f:"g"}]}

And you can eval() the resulting string:

var obj = eval(objStr)

Comments