Skip to content

Instantly share code, notes, and snippets.

@marek-saji
Created January 17, 2013 09:49
Show Gist options
  • Save marek-saji/4554910 to your computer and use it in GitHub Desktop.
Save marek-saji/4554910 to your computer and use it in GitHub Desktop.
Safe version of JSON.stringify. Discards functions, detects multiple references to same objects and introduces maximum depth.
function safeJSONStringify (input, maxDepth)
{
var output,
refs = [],
refsPaths = [];
maxDepth = maxDepth || 5;
function recursion (input, path, depth)
{
var output = {},
pPath,
refIdx;
path = path || "";
depth = depth || 0;
depth++;
if (maxDepth && depth > maxDepth)
{
return "{depth over " + maxDepth + "}";
}
for (var p in input)
{
pPath = (path ? (path+".") : "") + p;
if (typeof input[p] === "function")
{
output[p] = "{function}";
}
else if (typeof input[p] === "object")
{
refIdx = refs.indexOf(input[p]);
if (-1 !== refIdx)
{
output[p] = "{reference to " + refsPaths[refIdx] + "}";
}
else
{
refs.push(input[p]);
refsPaths.push(pPath);
output[p] = recursion(input[p], pPath, depth);
}
}
else
{
output[p] = input[p];
}
}
return output;
}
if (typeof input === "object")
{
output = recursion(input);
}
else
{
output = input;
}
return JSON.stringify(output);
}
@aberel
Copy link

aberel commented Jul 6, 2016

It's a great function, but I think is missing the "array" type, which here is considered as generic "object"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment