Skip to content

Instantly share code, notes, and snippets.

@xieranmaya
Created January 13, 2015 08:33
Show Gist options
  • Save xieranmaya/eb9e0cd7230eb5218354 to your computer and use it in GitHub Desktop.
Save xieranmaya/eb9e0cd7230eb5218354 to your computer and use it in GitHub Desktop.
var escapeJSON = (function() {
var _escape = function(string) {
string = string == null ? '' : '' + string;
return /(?:&|<|>|"|'|`)/.test(string) ? string.replace(/(?:&|<|>|"|'|`)/g, function(match) {
var escapeMap = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#x27;',
'`': '&#x60;'
};
return escapeMap[match];
}) : string;
};
var escapeJSON = function escapeJSON(json) {
var i, key;
if (Object.prototype.toString.call(json) == '[object Array]') {
for (i = 0; i < json.length; i++) {
json[i] = escapeJSON(json[i]);
}
return json;
} else if (Object.prototype.toString.call(json) == '[object Object]') {
for (key in json) {
if (json.hasOwnProperty(key)) {
json[key] = escapeJSON(json[key])
}
}
return json
} else if (typeof json == 'string') {
return _escape(json)
} else {
return json
}
};
return escapeJSON;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment