define([ "dojo/_base/declare", "dojo/json" ], function(declare, json) { var module = declare("obno.core.safejson", null, { }); /** * safely serialize an object to a json string by detecting and skipping circular refs * circular refs are replaced by a "$ref" attribute point to the __jsonRefID property of the referenced object * if no __jsonRefID property found then the referenced is skipped. */ module.stringify = function(value){ var seen = []; return json.stringify(value, function(k, v){ if (typeof v === 'object' && v !== null && !(Object.prototype.toString.call(v) === '[object Array]') && !(v instanceof Boolean) && !(v instanceof Date) && !(v instanceof Number) && !(v instanceof RegExp) && !(v instanceof String)){ //have we seen it? var seenIdx = seen.indexOf(v); if (seenIdx === -1){ //add it seen.push(v); return v; } //a circular ref var obj = seen[seenIdx]; return {"$ref": obj.__jsonRefID || "?"}; } return v; }); seen = []; }; return module; });