Escape Strings For JSON Output

Escape a string for embedding in JSON: quotes, backslashes, and control characters become the two-character or \uXXXX forms the spec requires.

JavaSecurity Boundaries

Code

snippet
public class JsonEscape {

    // JSON 字符串只允许安全字符:引号、反斜杠和控制字符必须转义
    static String escape(String value) {
        StringBuilder out = new StringBuilder(value.length() + 8);
        for (int i = 0; i < value.length(); i++) {
            char c = value.charAt(i);
            switch (c) {
                case '"'  -> out.append('\\').append('"');
                case '\\' -> out.append('\\').append('\\');
                case '\b' -> out.append('\\').append('b');
                case '\f' -> out.append('\\').append('f');
                case '\n' -> out.append('\\').append('n');
                case '\r' -> out.append('\\').append('r');
                case '\t' -> out.append('\\').append('t');
                default -> {
                    if (c < 0x20) {
                        out.append(String.format("\\u%04x", (int) c));
                    } else {
                        out.append(c);
                    }
                }
            }
        }
        return out.toString();
    }

    public static void main(String[] args) {
        for (String raw : new String[] {
                "say \"hi\"\nnew\\line", "tab\there", "ctrl:\u0007bell"}) {
            System.out.println(escape(raw));
        }
    }
}

How it works

Structurally, expect the class JsonEscape and the functions escape and main and nothing else.

Iteration happens inside for (int i = 0; i < value.length(); i++) — everything outside it runs once.

What to watch for

  • No dependency resolution ever happens; the toolchain alone suffices.

Using it

Entry signature: static String escape(String value)

main is the driver: it invokes escape before returning.

Key statements

return out.toString();

Interactive Tools for This Topic

FAQ

How do you run Escape Strings For JSON Output?
The runtime alone is enough: execute the file as a complete program.