Created
January 17, 2013 09:49
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's a great function, but I think is missing the "array" type, which here is considered as generic "object"