pub fn json_escape(json: &str) -> StringExpand description
Escapes a JSON string for a <script> element (Rails’ json_escape).
<, > and & become \u003c, \u003e and \u0026, and U+2028 and
U+2029 become escapes, so the JSON cannot close the script element or
break JavaScript parsing; it still parses to the same value.
§Examples
use ocre::security::json_escape;
let json = serde_json::json!({ "title": "</script><script>alert(1)</script>" }).to_string();
let safe = json_escape(&json);
assert_eq!(safe, r#"{"title":"\u003c/script\u003e\u003cscript\u003ealert(1)\u003c/script\u003e"}"#);
assert_eq!(serde_json::from_str::<serde_json::Value>(&safe)?["title"], "</script><script>alert(1)</script>");