Skip to main content

escape_json_script

Function escape_json_script 

Source
pub fn escape_json_script(json: &str) -> Cow<'_, str>
Expand description

Makes a JSON document safe to place inside a <script> element.

Inside <script> the HTML parser looks for </script and <!-- and knows nothing about JSON, so a string value holding </script><script>alert(1)</script> ends the element and starts another. <, > and & are therefore written as the JSON escapes \u003c, \u003e and \u0026, which any JSON parser reads back as the same characters, and U+2028/U+2029 (line terminators that were not legal inside a JavaScript string) as \u2028/\u2029. Valid JSON only has those characters inside string values, so the meaning of the document does not change.

This does not validate the JSON, and it is not escape_text: HTML-escaping would write &lt;, which JSON does not decode.

ยงExamples

use molt::core::escape::escape_json_script;
assert_eq!(
    escape_json_script(r#"{"a":"</script><b>&"}"#),
    r#"{"a":"\u003c/script\u003e\u003cb\u003e\u0026"}"#
);