Skip to main content

jigs_core/
json.rs

1//! JSON string escaping utility shared by rendering crates.
2
3use std::fmt::Write;
4
5/// Append a JSON-escaped, double-quoted string to `out`.
6///
7/// Escapes the usual JSON characters (`"`, `\`, `\n`, `\r`, `\t`, and
8/// control characters below U+0020). When `escape_html` is true,
9/// also escapes `<` as `\u003c` to prevent `</script>` injection when
10/// embedding JSON in HTML `<script>` tags.
11pub fn push_json_str(out: &mut String, s: &str, escape_html: bool) {
12    out.push('"');
13    for c in s.chars() {
14        match c {
15            '"' => out.push_str("\\\""),
16            '\\' => out.push_str("\\\\"),
17            '\n' => out.push_str("\\n"),
18            '\r' => out.push_str("\\r"),
19            '\t' => out.push_str("\\t"),
20            '<' if escape_html => out.push_str("\\u003c"),
21            c if (c as u32) < 0x20 => {
22                let _ = write!(out, "\\u{:04x}", c as u32);
23            }
24            c => out.push(c),
25        }
26    }
27    out.push('"');
28}