Skip to content

Instantly share code, notes, and snippets.

@kanakiyajay
Created August 21, 2014 11:39
Show Gist options
  • Save kanakiyajay/b8719e797d0f9190b464 to your computer and use it in GitHub Desktop.
Save kanakiyajay/b8719e797d0f9190b464 to your computer and use it in GitHub Desktop.
/*
* @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
* @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace.
* @returns {string|undefined} JSON-ified string representing `obj`.
*/
function toJson(obj, pretty) {
if (typeof obj === 'undefined') return undefined;
return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null);
}
function toJsonReplacer(key, value) {
var val = value;
if (typeof key === 'string' && key.charAt(0) === '$') {
val = undefined;
} else if (isWindow(value)) {
val = '$WINDOW';
} else if (value && document === value) {
val = '$DOCUMENT';
} else if (isScope(value)) {
val = '$SCOPE';
}
return val;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment