JSON guide

JSON.stringify escape quotes problem

JSON.stringify adds backslashes before quotes when JSON text is being stored inside another string.

Open JSON Formatter View all tools

Why quotes get backslashes

Quotes end a JSON string, so quotes inside the string have to be escaped. JSON.stringify is doing the correct thing. The confusing part is usually the data shape: you expected an object, but the value you are looking at is a string that contains JSON text.

Example

Input

JSON.stringify({ payload: { ok: true } })

Output

{"payload":{"ok":true}} when stringified once; extra backslashes appear when that text is stringified again.

How to inspect escaped JSON

  1. Check the type first: object, JSON string, or a string that contains another JSON value.
  2. If the whole value starts and ends with quotes, parse that outer string layer before formatting the inner JSON.
  3. Do not delete backslashes by search and replace. Let JSON.parse handle the string layer.
  4. Stringify again only when the next field really expects text.

One layer or two layers

A normal object serialized once should not be full of backslash-quote sequences except inside string fields. If the entire value is wrapped in quotes and every inner quote is escaped, you are looking at JSON text stored as a string.

Logs, queues, database text columns, and message fields do this all the time. Decode the outer string first, then format the inner value.

When escaped quotes are correct

Escaped quotes are not a bug by themselves. They are required when the data contains quote characters. The bug is sending the escaped string to code that expected the original object.

Before changing code, check the field contract. A text column may want a string. A JSON request body probably wants the object or array.

Common mistakes

  • Stringifying a value that was already serialized
  • Removing backslashes by search and replace and changing the data
  • Sending a JSON string where an API expects an object
  • Assuming escaped quotes mean the JSON is invalid

Related problems

FAQ

Why does JSON.stringify add backslashes before quotes?

Quotes inside a JSON string must be escaped so the string remains valid JSON.

Should I remove the backslashes manually?

No. Parse the JSON string layer instead of editing escape characters by hand.

Does escaped JSON mean invalid JSON?

No. It can be valid JSON, but it may be one string layer away from the object you meant to inspect.