Created
August 1, 2017 12:00
-
-
Save antoni/5e2d36341df5b41a3bbdec00359e150d to your computer and use it in GitHub Desktop.
Dumps an object in JSON. Works with circular JSON structures
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
// Dumps an object in JSON. Works with circular structures like: | |
// | |
// var o = {}; | |
// o.o = o; | |
JSON.stringifyOnce = function(obj, replacer, indent){ | |
var printedObjects = []; | |
var printedObjectKeys = []; | |
function printOnceReplacer(key, value){ | |
if ( printedObjects.length > 2000){ // browsers will not print more than 20K, I don't see the point to allow 2K.. algorithm will not be fast anyway if we have too many objects | |
return 'object too long'; | |
} | |
var printedObjIndex = false; | |
printedObjects.forEach(function(obj, index){ | |
if(obj===value){ | |
printedObjIndex = index; | |
} | |
}); | |
if ( key == ''){ //root element | |
printedObjects.push(obj); | |
printedObjectKeys.push("root"); | |
return value; | |
} | |
else if(printedObjIndex+"" != "false" && typeof(value)=="object"){ | |
if ( printedObjectKeys[printedObjIndex] == "root"){ | |
return "(pointer to root)"; | |
} else{ | |
return "(see " + ((!!value && !!value.constructor) ? value.constructor.name.toLowerCase() : typeof(value)) + " with key " + printedObjectKeys[printedObjIndex] + ")"; | |
} | |
}else{ | |
var qualifiedKey = key || "(empty key)"; | |
printedObjects.push(value); | |
printedObjectKeys.push(qualifiedKey); | |
if(replacer){ | |
return replacer(key, value); | |
}else{ | |
return value; | |
} | |
} | |
} | |
return JSON.stringify(obj, printOnceReplacer, indent); | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment