Created
December 19, 2013 21:12
-
-
Save baudehlo/8046352 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
var util = require('util'); | |
function json_stringify_safe(node, parents){ | |
parents = parents || []; | |
console.log("Looking at: ", node); | |
if(!node || typeof node != "object" || util.isDate(node) || util.isError(node) || util.isRegExp(node)){ | |
return JSON.stringify(node); | |
} | |
console.log("Type: ", typeof node); | |
if (util.isArray(node)) { | |
parents.push(node); | |
var str = '['; | |
for (var i=0; i < node.length; i++) { | |
var value = node[i]; | |
if (value && typeof value == "object" && parents.indexOf(value) >= 0) { | |
// circularity detected! | |
str += '"[Circular]"'; | |
} | |
else { | |
str += json_stringify_safe(value, parents); | |
} | |
if (i != (node.length - 1)) { | |
str += ','; | |
} | |
} | |
parents.pop(); | |
return str + ']'; | |
} | |
var keys = Object.keys(node); | |
parents.push(node); // add self to current path | |
var str = '{'; | |
for (var i = 0; i < keys.length; i++) { | |
str += JSON.stringify(keys[i]) + ':'; | |
var value = node[keys[i]]; | |
if (value && typeof value == "object" && parents.indexOf(value) >= 0) { | |
// circularity detected! | |
str += '"[Circular]"'; | |
} | |
else { | |
str += json_stringify_safe(value, parents); | |
} | |
if (i != (keys.length - 1)) { | |
str += ','; | |
} | |
} | |
parents.pop(); | |
return str + '}'; | |
} | |
var list = ["a", "b", "c"]; var obj = {list: list, foo: {bar: list}}; | |
list.push(obj); | |
console.log(json_stringify_safe(obj)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment