Skip to content

Instantly share code, notes, and snippets.

@subzey
Created September 22, 2016 15:02
Show Gist options
  • Select an option

  • Save subzey/21483cb89f4027898cdf2bdf625f94a2 to your computer and use it in GitHub Desktop.

Select an option

Save subzey/21483cb89f4027898cdf2bdf625f94a2 to your computer and use it in GitHub Desktop.
// Create regexp once
var reUnicode = /[\u0080-\uFFFF]/g;
// Create functor once
function _unicodeEscape(character) {
return '\\u' + ('000' + character.charCodeAt(0).toString(16)).slice(-4);
}
function escapeJSON(jsonStr) {
// This function only accepts valid JSON strings
return jsonStr.replace(reUnicode, _unicodeEscape);
}
// Usage:
var str = escapeJSON(JSON.stringify(
{
"проверка": "проверка",
"\r\n\t": true
}
));
console.assert(JSON.parse(str)['проверка'] === 'проверка'); // Should work
console.assert(JSON.parse(
escapeJSON('"\\u0442ест"')
) === 'тест'); // Should not escape already escaped chars
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment