Skip to content

Instantly share code, notes, and snippets.

@munro
Created October 19, 2023 18:22
Show Gist options
  • Save munro/e645055d021fbd07a700fe37c5c5ece0 to your computer and use it in GitHub Desktop.
Save munro/e645055d021fbd07a700fe37c5c5ece0 to your computer and use it in GitHub Desktop.
Encode JSON & Escape Unicode in JavaScript
// Similar to json.dumps(obj, *, ensure_ascii=True) in Python
function encodeJsonUnicode(obj) {
return JSON.stringify(obj).replace(/[^\0-\x7F]/g, (c) => {
return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
});
}
// decoding is simply JSON.parse(...);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment