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.
Code
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
Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.Regex Escape GeneratorEscape plain text so it can be embedded safely in a JavaScript RegExp, covering all metacharacters like dots, brackets, braces, and backslashes.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.
FAQ
- How do you run Escape Strings For JSON Output?
- The runtime alone is enough: execute the file as a complete program.
Report a problem with this exampleOpens a pre-filled issue on GitHub.