Escape JSON as a String Literal (and Decode Double-Encoded JSON)

Stringifying JSON wraps it in quotes and escapes the inner quotes and special characters, producing a JSON string literal you can safely embed elsewhere.

What stringifying to a literal means

Passing a JSON string to JSON.stringify wraps it in double quotes and escapes the inner quotes and backslashes, producing a single string value that is safe to embed.

Why you need it

Embedding JSON inside another JSON field, storing JSON in a string database column, or passing JSON as an environment variable or URL parameter all require an escaped string literal.

Escaping rules

Double quotes are escaped with a backslash, backslashes are doubled, and control characters such as newline and tab become their two-character escape sequences. The result contains no raw line breaks.

Decoding double-encoded JSON

If you receive a string that begins with an escaped quote and contains escaped-quote sequences, it was stringified. Parse it once to recover the inner JSON string, then parse again to get the actual value.

Where double-encoding shows up

Logging frameworks that serialise context objects, webhook payloads that wrap a JSON body inside a 'body' field, message queues that send JSON-as-string envelopes, and database columns typed as text or varchar are the most common sources. Look for a leading quote and an even number of backslashes.

Working with embedded JSON in logs

Structured loggers often stringify objects to keep each log line a single value. To inspect, pull the line out of the log viewer, unescape with JSON.parse, then format the recovered JSON. Avoid grepping a multiline JSON object — JSON stringified to one line is much easier to search.

Tools for the round-trip

Browser console: JSON.parse(line) returns the inner JSON, then JSON.stringify(...,null,2) pretty-prints. Node CLI: 'node -e "console.log(JSON.parse(process.argv[1]))" "<line>"' does both steps. The JSON Stringify tool on this site handles arbitrarily deep nesting in one click.