Escape JSON String

Examples:

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	tab

Output:

"Hello \"world\"\nNew line\ttab"

Escape sequence table

CharacterEscaped asNotes
"\"Double quote
\\\Backslash (escaped first)
newline\nLine feed
carriage return\rCarriage return
tab\tHorizontal tab
Non-ASCII (optional)\uXXXXUnicode escape

Where escaping is needed

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

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:

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 automatically

CLI (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

Frequently asked questions

What does escaping a JSON string do?
Escaping replaces special characters with backslash sequences so the text can be safely embedded inside a code string literal or as a value inside another JSON object. Double quotes are prefixed with a backslash, newlines become a backslash followed by the letter n, tabs become a backslash followed by the letter t, and backslashes themselves are doubled. The result is a single line that will not break the surrounding syntax.
When should I escape Unicode?
Escape Unicode when you need pure ASCII output — for example, when sending data to legacy systems that do not handle UTF-8, or when you want to avoid encoding issues in transit. Non-ASCII characters are replaced with the Unicode escape form, which is a backslash, a lowercase u, and four hex digits. For modern systems, leave it off and preserve the original characters.
What is the difference between escaping and encoding?
Escaping adds backslash sequences inside a string literal for the few characters that would otherwise break the syntax. Encoding, such as Base64 or URL encoding, transforms the entire string into a different representation. This tool does escaping, not encoding. Use a URL encoder for query parameters and a Base64 encoder for binary data.
Can I escape a string that already has backslashes?
Yes. The tool handles existing backslashes correctly — each backslash in the input is doubled in the output, which prevents double-escaping issues. This matters for Windows file paths and regular expressions, where backslashes are common and meaningful.
How do I escape a string in JavaScript?
Use JSON.stringify. Passing a string to JSON.stringify returns a quoted JSON string literal with all special characters escaped. This tool does the same thing, with additional options for Unicode escaping and for targeting JavaScript, Python, Java, or C#.
Why does my escaped output look different from my input?
The tool escapes backslashes first, then quotes, then control characters. This order prevents double-escaping: a backslash in the input becomes two backslashes, and a quote becomes a backslash followed by a quote. Newlines and tabs become their short escape forms. The result is a single-line string literal.
Which target languages are supported, and does it matter which one I pick?
JavaScript, Python, Java, and C# are supported. For most text the output is identical across all four, because they share the same escape sequences for quote, backslash, newline, tab, and carriage return. The differences only appear at the edges — how each language formats the Unicode escape, and whether a single-quoted or verbatim string is an option. Pick the language you will paste the literal into so the quote style and Unicode form match.
Does the tool modify my input or send it anywhere?
No. Everything runs locally in your browser. The input is preserved in the editor, and the escaped output appears in a separate panel. No server calls are made, so the tool is safe to use with sensitive data.

Related tools