hbms hbms - 20 days ago 5
Javascript Question

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

This question has been resolved.

Based on the answer from karuzo, I made a finalized version:

$['to'] = function ($a)
{
$u = JSON.stringify(this); $w = this.typeof(); $x = $a.typeof();

if ($x == 'Array')
{
if ($w == 'Object')
{
$y = []; this.keys().for(($l, $m, $n) =>
{
$y[$m] = [$l, this[$l]];
});

return $y;
}

else if ($w == 'Array')
{
return [].slice.call(this);
}

else if ($w == 'String')
{
return [this];
};
}

else if ($x == 'Object')
{
if ($w == 'Object')
{
return this.to("").from({});
}

else if ($w == 'Array')
{
$y = {}; this.for(($l, $m, $n) =>
{
$l != {}._ ? $y[$m] = $l : null;
});

return $y;
}

else if ($w == 'String')
{
return {value: this};
}
}

else if ($x == 'String')
{
if ($w == 'Object')
{
return JSON.stringify(this).replace(/\"([^(\")"]+)\":/g, '$1:');
}

else if ($w == 'Array')
{
return $u;
}

else if ($w == 'String' | $w == 'Number')
{
return this.toString();
};
}

else
{
return this;
};
}


This version is included directly in paxiom.js, the file which the code resides.
Some of the functions used in the above code are in the library. I know this tends to get some viewers, so when the library's version #1 is finished, it will be available at https://hbms.github.io/-/paxiom.js

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