Skip to content

Instantly share code, notes, and snippets.

@matthewmueller
Created August 25, 2012 02:50
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save matthewmueller/3459332 to your computer and use it in GitHub Desktop.
Save matthewmueller/3459332 to your computer and use it in GitHub Desktop.
Escape JSON strings before trying to run JSON.parse
/*
Escape JSON
*/
var escapeJSON = exports.escapeJSON = function(json) {
var escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
var meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
};
escapable.lastIndex = 0;
return escapable.test(json) ? '"' + json.replace(escapable, function (a) {
var c = meta[a];
return (typeof c === 'string') ? c
: '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + json + '"';
};
@MauScheff
Copy link

Thanks!

@maikol8-10
Copy link

Thanks bro!!!!

@asjustis
Copy link

Omg, this worked. Happy I don't need to write this one myself :D Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment