Escape JSON String
100% in your browser
Your data is never uploaded. All processing happens locally on your device.
Read privacy policy →Last updated: 2026-09-17
Paste JSON or any text to escape it into a string literal. Choose your target language (JavaScript, Python, Java, C#), toggle Unicode escaping, and wrap in quotes. Everything runs locally — no server calls.
What this tool does
Escapes text or JSON into a string literal by replacing special characters with backslash sequences. You can wrap the output in quotes, escape non-ASCII characters to \uXXXX, and target the output for JavaScript, Python, Java, or C#. The escaping is reversible — the unescape tool restores the original.
Example
Input:
{"name":"test","value":42}Output (with quote wrapping):
"{\"name\":\"test\",\"value\":42}"Input with special characters:
Hello "world"
New line tabOutput:
"Hello \"world\"\nNew line\ttab"Escape sequence table
| Character | Escaped as | Notes |
|---|---|---|
" | \" | Double quote |
\ | \\ | Backslash (escaped first) |
| newline | \n | Line feed |
| carriage return | \r | Carriage return |
| tab | \t | Horizontal tab |
| Non-ASCII (optional) | \uXXXX | Unicode escape |
Where escaping is needed
- Embedding JSON as a string value inside another JSON object:
{"payload": "{\"name\":\"test\"}"} - Storing text in database fields that will be serialized as JSON.
- Passing data through log pipelines where control characters could break the log format.
- Generating code that contains string literals with user-provided content.
Escaping for database storage
When a JSON document lives inside a single text or VARCHAR column, the column value is a JSON string. The moment you serialize a row containing that column back into JSON — for an export, an API response, or a message queued for another service — the inner quotes have to be escaped or the outer structure breaks. The same applies to audit-log tables that keep the original request body as a JSON-typed field.
Consider an orders table with a raw_payload column typed as TEXT. One row stores:
{"order_id":42,"note":"paid in full"}If a downstream consumer needs that payload as a JSON string value (a quoted JSON literal) rather than as a raw JSON object, run it through this tool with quote wrapping on. The output is:
"{\"order_id\":42,\"note\":\"paid in full\"}"Store that escaped form in the column, or embed it directly into the outer document’s payload field, and the consumer can parse it as a JSON string in one step. The unescape tool reverses the transform when you need the original object back.
The trap to avoid is serializing twice. If your database driver already returns the column as a JSON string, and you then pass that string through this tool before writing it into an export file, you get two layers of escaping. Apply escaping exactly once, at the boundary where the string enters its container.
Escaping for log pipelines
Structured logging libraries — the Python logging module with a JSON formatter, Serilog in .NET, Logstash’s json codec — accept arbitrary string fields and serialize them. When a field value contains a newline, a quote, or a backslash, the logger escapes it automatically. But if you build the log line by hand, concatenating strings into a JSON-shaped template, you have to escape each field yourself. A single newline in a user-supplied message will break the line and corrupt the next log entry.
Suppose a web handler logs incoming request bodies with a hand-built template:
{"level":"info","message":"<USER MESSAGE HERE>","request_id":"abc-123"}If the user message is inserted raw and really does contain a line break, the log file gets a physical newline in the middle of the JSON line. File-based shippers like Filebeat that split on newlines by default will treat the second half as a separate, malformed entry, and your log viewer will show a broken record where the request_id has drifted onto its own line.
Running just the user message through this tool with quote wrapping on turns the embedded line break into the two-character escape sequence, so the whole log line stays on one physical line:
"User said: hello\nworld"Drop that into the message field and the surrounding JSON stays parseable, one entry per line. The same approach handles tabs, which some terminals render as wide whitespace and shift columns in log viewers, and stray carriage returns left over from Windows line endings.
Common mistakes when escaping
- Escaping the same string twice. Each pass doubles the backslashes, so a quote that was one backslash plus a quote becomes two backslashes plus a quote on the second pass, and the unescape tool reports two levels. Apply escaping exactly once, at the boundary where the string enters its container.
- Escaping quotes before backslashes. If you escape quotes first, every backslash already in the input ends up prefixing the next character, turning
C:\tempinto a broken escape. Always escape backslashes first, which is what this tool does. - Pasting an already-escaped string back in to “fix” it. The result is double-escaped. Use the unescape tool to remove a layer instead of re-escaping.
- Assuming the output is valid JSON on its own. With quote wrapping off, the escaped content is a string body, not a complete JSON value. Wrap it in quotes, or toggle the option on, before embedding it.
- Forgetting that single quotes are not special in JSON. A single quote in the input is left untouched, because JSON string literals are delimited by double quotes. Do not pre-replace single quotes.
- Leaving Unicode escaping on for normal traffic. It is optional and exists for ASCII-only pipelines. For ordinary UTF-8 data it bloats the output and makes emoji and accented letters unreadable in diffs.
Unicode escaping and surrogate pairs
When Unicode escaping is on, every non-ASCII character is replaced with the short Unicode escape form: a backslash, a lowercase u, and four hex digits. Characters in the Basic Multilingual Plane — code points up to U+FFFF — fit in a single four-digit escape, so é becomes \u00e9 and € becomes \u20ac.
Characters above the BMP — emoji, rare CJK ideographs, some historic scripts — have code points above U+FFFF and do not fit in four hex digits. JSON, and JavaScript which inherited the format, represents these as a surrogate pair: two four-digit escapes that together encode one character. The grinning face emoji 😀, which is U+1F600, becomes \uD83D\uDE00. The first escape is the high surrogate, in the range D800 to DBFF, and the second is the low surrogate, in the range DC00 to DFFF.
The tool emits these pairs the same way JavaScript’s JSON.stringify does, so the output round-trips through JSON.parse and through the matching unescape tool without losing the character. If you turn Unicode escaping off, the original character is preserved verbatim and the output stays UTF-8. That is usually the better choice for modern systems: the output is shorter, diffs stay readable, and nothing is lost.
Escaping for different target languages
The four target languages — JavaScript, Python, Java, and C# — agree on the core escape sequences this tool produces. In all four, a backslash is escaped as two backslashes, a double quote as a backslash followed by a double quote, a newline as backslash-n, a tab as backslash-t, and a carriage return as backslash-r. For the common case of embedding plain text or JSON into a double-quoted string literal, the output is interchangeable between the four.
The differences are narrow and mostly about quote style and Unicode formatting:
- JavaScript uses double-quoted JSON string literals, and its native Unicode escape is the
\uXXXXform with surrogate pairs above the BMP, which is exactly what the tool emits. - Python accepts the same
\uXXXXform in normal string literals, and also supports an eight-digit form for code points above the BMP. The tool’s surrogate-pair output is valid Python, because Python parses each\uescape independently. - Java uses the same
\uXXXXform and the same surrogate-pair convention. Java source files are UTF-16 internally, so the output maps cleanly onto a JavaStringliteral. - C# accepts
\uXXXXin regular string literals and also offers verbatim strings, where quotes are doubled instead of escaped. The tool targets regular C# string literals, not verbatim ones, so if you paste the output into a verbatim string you will get literal backslashes in the result.
If your target is a single-quoted Python or JavaScript string, switch the literal to double quotes. Single quotes are not escaped by the tool, so a single quote in the input would terminate your literal early.
Escaping for code generation
When a build step or scaffold script emits source files that contain string literals, any value drawn from user input, configuration, or a database has to be escaped before it is interpolated into the generated source. A single double quote in a config value terminates the literal early, and the compiler or interpreter raises a syntax error — or worse, silently parses the remainder of the line as code.
A typical generator reads a list of display labels from a config file and writes a TypeScript module that exports them as constants. If a label contains a quote and is pasted raw into the template, the emitted file is broken. Running each label through this tool with quote wrapping on and JavaScript selected as the target produces a literal the TypeScript compiler accepts unchanged, because TypeScript shares JavaScript’s string literal rules. The same pattern covers Java property bundles, C# resource files, and Python configuration modules: escape the value once, at the point where it enters the literal, and the generated artifact parses without post-processing.
Keep the raw, unescaped source as the canonical value in your data. Store the escaped form only in the emitted artifact. If you persist the escaped version as the source of truth, every downstream consumer that does not need a code literal — a report, a display layer, an API client — has to unescape it before use, and the risk of double-escaping goes up.
Escaping versus sanitization and validation
Escaping is not sanitization, and it is not validation. The three serve different purposes and operate at different points in a pipeline.
Validation rejects input that does not meet a contract — a field that must be an email, a number in an allowed range, a string shorter than a limit. Validation runs before the value is stored or passed downstream, and it answers the question “is this acceptable?” Escaping never rejects anything; it transforms the input so it is safe to embed in a given context, and every character of the original is recoverable through unescaping.
Sanitization removes or replaces content that is dangerous in a specific context — stripping HTML tags from a value that will be rendered into a web page, or removing shell metacharacters from a value that will be passed to a command. Sanitization is lossy: the original cannot always be recovered. Escaping is lossless.
Use all three where they apply. Validate the shape and bounds of incoming data. Escape it when it enters a string literal, a JSON value, or a log field. Sanitize it when it enters a context that interprets content — HTML, SQL, shell commands — and use the sanitizer built for that context, not a generic backslash escape. This tool handles the string-literal and JSON-value context; it does not make a value safe to interpolate into HTML or SQL.
Reading escaped output in diffs and reviews
Escaped output is dense. A paragraph of natural language with a few quotes and line breaks compresses into a single line of backslash sequences, and code review tools that wrap long lines can make it harder to read, not easier. When a diff adds an escaped payload field, the reviewer sees a wall of backslashes where the original message is not obvious.
Two habits make review faster. First, keep Unicode escaping off unless the downstream pipeline demands pure ASCII — preserving the original characters means accented letters and emoji stay visible in the diff, and a reviewer can read the actual text instead of decoding hex. Second, when reviewing a change that touches escaped fields, paste the escaped value into the unescape tool to see the original. That is faster than mentally decoding each sequence, and it catches double-escaping immediately: if the unescape tool reports two or more levels, the string was escaped more than once somewhere upstream.
For pull requests that add or modify escaped payloads, describe the raw value in the description and attach or link the escaped form. The reviewer reads prose; the machine reads escapes.
Round-tripping and reversibility
Every transform this tool performs is reversible. Because no characters are dropped — only replaced with longer sequences — the unescape tool can reconstruct the original input exactly, including whitespace, control characters, and Unicode. This is a stronger guarantee than sanitization or truncation, which are lossy by design.
The reversibility depends on the escape order. Backslashes are escaped first, so when the unescape tool reads a backslash in the escaped output, it knows the next character is part of an escape sequence, not a literal backslash that was already in the input. If the order were reversed, a sequence like backslash-n in the original input would be indistinguishable from a real newline after escaping. The fixed order — backslashes, then quotes, then control characters, then Unicode — keeps the transform unambiguous.
Security considerations
Escaping prevents syntax-breaking and structural corruption, not injection. If an untrusted string will be interpolated into HTML, a SQL query, or a shell command, backslash escaping for JSON is the wrong defense. Use the context-specific sanitizer: HTML-encoding for content rendered into a page, parameterized queries for SQL, and allowlisted argument arrays for shell calls.
Within its scope, escaping does close one class of problem: a crafted input containing quotes and backslashes cannot break out of the string literal it is placed in, because every quote and backslash is neutralized. That is enough for JSON values, log fields, and code literals — contexts where the surrounding parser only cares about delimiter characters. For any context that interprets content after parsing — HTML, SQL, URLs with query parameters — pair escaping with the appropriate context sanitizer.
Performance, limits, and large inputs
The tool processes the input in a single pass, character by character, and the output grows in proportion to the input. Strings that contain many backslashes or quotes expand more, because each of those characters becomes two characters in the output, but the growth factor is bounded: at worst the output is twice the input length plus the wrapping quotes. Unicode escaping expands non-ASCII characters more aggressively — a single emoji above the BMP becomes twelve characters when emitted as a surrogate pair, so a document dense with emoji can grow several times over.
There is no hard size limit imposed by the tool. The constraint is browser memory and editor responsiveness. Past a few megabytes, the input editor may lag, and the output panel will hold a string several times that size when Unicode escaping is enabled. For batch processing of many large documents, run the escape step in a script with the language’s native serializer — json.dumps in Python, JSON.stringify in Node — instead of pasting each document into the browser by hand.
Do it in code
JavaScript:
const escaped = JSON.stringify(input);
// With Unicode escaping:
const escapedUnicode = JSON.stringify(input).replace(/[^\x00-\x7F]/g, ch =>
'\\u' + ch.charCodeAt(0).toString(16).padStart(4, '0'));Python:
import json
escaped = json.dumps(input)
# json.dumps escapes quotes and control characters automaticallyCLI (jq):
echo 'Hello "world"' | jq -Rs '.'jq -Rs reads the entire input as a string and outputs it as a JSON string literal.
Edge cases handled
- Existing backslashes are escaped first to prevent double-escaping.
- Unicode characters above the BMP (emoji, rare scripts) are escaped as surrogate pairs (
\uD83D\uDE00) when Unicode escaping is enabled. - The tool preserves all input characters — no data is lost during escaping.
- Quote wrapping can be toggled off to produce just the escaped content without surrounding quotes.