Created
March 21, 2014 12:11
-
-
Save cmc19/9684866 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
(function (root) { | |
root.stringifySafe = stringify; | |
function stringify(obj, fn, spaces, decycle) { | |
return JSON.stringify(obj, getSerialize(fn, decycle), spaces); | |
function getSerialize(fn, decycle) { | |
var seen = [], keys = []; | |
decycle = decycle || function (key, value) { | |
return '[Circular ' + getPath(value, seen, keys) + ']' | |
}; | |
return function (key, value) { | |
var ret = value; | |
if (typeof value === 'object' && value) { | |
if (seen.indexOf(value) !== -1) | |
ret = decycle(key, value); | |
else { | |
seen.push(value); | |
keys.push(key); | |
} | |
} | |
if (fn) ret = fn(key, ret); | |
return ret; | |
} | |
} | |
function getPath(value, seen, keys) { | |
var index = seen.indexOf(value); | |
var path = [keys[index]]; | |
for (index--; index >= 0; index--) { | |
if (seen[index][path[0]] === value) { | |
value = seen[index]; | |
path.unshift(keys[index]); | |
} | |
} | |
return '~' + path.join('.'); | |
} | |
} | |
})(JSON); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment