Skip to content

Instantly share code, notes, and snippets.

@malectro
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save malectro/2f010d729605b5c219c8 to your computer and use it in GitHub Desktop.
Save malectro/2f010d729605b5c219c8 to your computer and use it in GitHub Desktop.
Escapes the HTML of all strings attached to a JSON encodable object before stringifying it. Does not detect cycles.
var _ = require('underscore');
var escape = require('escape-html');
function recur(item) {
var ret;
if (_.isObject(item) || _.isArray(item)) {
ret = new item.constructor();
_.each(item, function (val, key) {
ret[key] = recur(val);
});
} else if (_.isString(item)) {
ret = escape(item);
} else {
ret = item;
}
return ret;
}
module.exports = function (item) {
JSON.stringify(recur(item));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment