Created
June 26, 2019 07:29
-
-
Save mathiasbynens/d6e10171d44a59bb5664617c64ff2763 to your computer and use it in GitHub Desktop.
Escaping JSON-stringified data for use as a JavaScript string literal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This object contains a string value that in contains a single quote, | |
// a double quote, a backtick, and a backslash. | |
const data = { foo: `a'b"c\`d\\e` }; | |
// Turn the data into its JSON-stringified form. | |
const json = JSON.stringify(data); | |
// Now, we want to insert the data into a script body as a JavaScript | |
// string literal per https://v8.dev/blog/cost-of-javascript-2019#json, | |
// escaping special characters like `"` in the data. | |
// With https://github.com/tc39/proposal-json-superset, the output of | |
// JSON.stringify is guaranteed to be syntactically valid ECMAScript, | |
// so let’s just use that: | |
const jsStringLiteral = JSON.stringify(json); | |
// Note: if you’re aiming to inject this script body into a <script> | |
// within an HTML document, you need additional escaping per | |
// https://mths.be/etago. In such cases, instead of JSON.stringify, | |
// consider using a specialized utility such as jsesc with | |
// its `isScriptContext: true` setting: | |
// https://github.com/mathiasbynens/jsesc#isscriptcontext | |
// Create the final script body. | |
const scriptBody = `const data = JSON.parse(${ jsStringLiteral });`; | |
// Log the result. | |
console.log(scriptBody); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment