Created
March 7, 2016 14:48
-
-
Save mladenp/3d00e5b9b54eb716fcb0 to your computer and use it in GitHub Desktop.
Prevent Circular JSON
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
/** | |
* Traverses a javascript object, and deletes all circular values | |
* @param source object to remove circular references from | |
* @param censoredMessage optional: what to put instead of censored values | |
* @param censorTheseItems should be kept null, used in recursion | |
* @returns {undefined} | |
*/ | |
function preventCircularJson(source, censoredMessage, censorTheseItems) { | |
//init recursive value if this is the first call | |
censorTheseItems = censorTheseItems || [source]; | |
//default if none is specified | |
censoredMessage = censoredMessage || "CIRCULAR_REFERENCE_REMOVED"; | |
//values that have allready apeared will be placed here: | |
var recursiveItems = {}; | |
//initaite a censored clone to return back | |
var ret = {}; | |
//traverse the object: | |
for (var key in source) { | |
var value = source[key] | |
if (typeof value == "object") { | |
//re-examine all complex children again later: | |
recursiveItems[key] = value; | |
} else { | |
//simple values copied as is | |
ret[key] = value; | |
} | |
} | |
//create list of values to censor: | |
var censorChildItems = []; | |
for (var key in recursiveItems) { | |
var value = source[key]; | |
//all complex child objects should not apear again in children: | |
censorChildItems.push(value); | |
} | |
//censor all circular values | |
for (var key in recursiveItems) { | |
var value = source[key]; | |
var censored = false; | |
censorTheseItems.forEach(function (item) { | |
if (item === value) { | |
censored = true; | |
} | |
}); | |
if (censored) { | |
//change circular values to this | |
value = censoredMessage; | |
} else { | |
//recursion: | |
value = preventCircularJson(value, censoredMessage, censorChildItems.concat(censorTheseItems)); | |
} | |
ret[key] = value | |
} | |
return ret; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment