JSON Escape & Unescape: Handling Nested Data Correctly

2024-04-15

Queues, logs, and DB columns often store JSON as a string inside JSON. Understanding escapes is essential to unwrap these payloads.

Characters that must be escaped

In strings: ", \, and control chars like \n and \t.

{
  "quote": "He said \"Hello\"",
  "path": "C:\\temp\\data"
}

JSON nested as a string

Outer parse first, then JSON.parse the inner string field.

{ "payload": "{\"id\":1,\"name\":\"Alice\"}" }

Double escaping in logs

Do not count backslashes by hand—parse repeatedly until you reach an object or the expected string.

Safe unescaping

Use JSON.parse, not regex replacements. Validate structure after parsing untrusted data (e.g. __proto__ keys).

Other contexts (SQL, shell)

JSON escaping ≠ SQL or shell quoting. Build objects, JSON.stringify, then apply context-specific escaping.

Recommended workflow

Paste → parse → format → inner parse on remaining string fields → business validation.