How to trace escaped JSON inside an event payload
Decode a label-printing event one layer at a time. Distinguish a newline from literal backslash-n and find which producer introduced an invalid inner document.
How we checked this guide. We parsed the outer and inner documents separately in Node.js and compared the decoded strings with the formatter’s round-trip output. Editorial and testing standards
Read the envelope before decoding the body
Consider a label-printing event sent through a queue. The queue uses a common envelope with an event name and a body field. The envelope contract requires the body to be a string, while the printing service expects that string to contain a small JSON object. The original message below is one complete JSON document. Quotation marks inside the body are escaped so they can travel inside the outer string without ending it.
Start by pasting the entire line into JSON Formatter and validating it. Inspect the value type of body. A formatted view may make its contents readable while leaving the actual value a string. The opening brace visible inside the string is the first character of the inner document. It belongs to the value at this stage. You can inspect the inner document separately after decoding the outer string.
{"event":"label.printed","body":"{\"lines\":[\"Rack A\",\"Bay 2\"],\"copies\":2}"}{"lines":["Rack A","Bay 2"],"copies":2}Use one parse for each documented text boundary
Recreate the message from values in a JavaScript console. The first serialization represents the printing instructions as text. The second represents the queue envelope as text. On the receiving side, record the type after each parse. Reading body from the decoded envelope gives a string. Parsing that string produces an object whose lines member is an array. The final check retrieves the second line and the number of copies, two values a printer would actually use.
If the queue client already delivers a decoded envelope object, start at its body property. Parsing the same envelope again would pass the wrong type to the parser. Other APIs deliver the body itself as an object. In that case a second parse is unnecessary. Compare the runtime type with the documented contract before changing the number of decoding steps. The appearance of a value in a console or logging dashboard is an unreliable count of how many steps remain.
Decide how to handle a field that contains the text null. Parsing that text succeeds and returns the value null. Reading printing options from it would still fail. A consumer expecting instructions can check that the decoded value is an object, that it is neither null nor an array, and that lines contains strings before taking a job. A separate type error can then identify a message that was grammatically valid at both layers.
const instructions = { lines: ["Rack A", "Bay 2"], copies: 2 };
const wire = JSON.stringify({
event: "label.printed",
body: JSON.stringify(instructions)
});
const envelope = JSON.parse(wire);
const job = JSON.parse(envelope.body);
console.log(typeof envelope.body, Array.isArray(job.lines));
// string true
console.log(job.lines[1], job.copies); // Bay 2 2Tell a line break from the two characters backslash and n
The visually confusing case is a printer note that contains a line break. In the first example in the table, the final note contains three characters, A, a line feed, and B. JSON represents a line feed inside a string with an escape. When that representation becomes the body string in the envelope, its backslash needs another level of escaping. Both encodings follow directly from serializing the values in order.
In the second example, someone actually typed A, a backslash, a lowercase n, and B into the note. Its length is four and it should print on a single line if the printer displays those characters literally. The inner representation therefore escapes a literal backslash. If you strip backslashes globally to tidy the log display, these two different notes can acquire the same apparent meaning. Test the value at the printing boundary by counting its characters and inspecting the character between A and B.
for (const note of ["A\nB", "A\\nB"]) {
const wire = JSON.stringify({ body: JSON.stringify({ note }) });
const decoded = JSON.parse(JSON.parse(wire).body).note;
console.log(decoded.length, decoded.charCodeAt(1));
}
// 3 10 (line feed)
// 4 92 (backslash)| Original envelope text | Inner JSON text | Final note length |
|---|---|---|
| {"body":"{\"note\":\"A\\nB\"}"} | {"note":"A\nB"} | 3 characters |
| {"body":"{\"note\":\"A\\\\nB\"}"} | {"note":"A\\nB"} | 4 characters |
Find the layer that owns a parse error
Try the malformed fixture below. Validating the entire envelope succeeds. After extracting body, validating its contents fails because a comma follows the final array entry. The outer sender was free to store any string in body, including a string that another service cannot read as JSON. An envelope validation check can pass for every message in a batch while the printing service still rejects one job.
When recording an error, name the layer and use offsets from that layer's input. An error position in the decoded body refers to the string that starts with the inner opening brace. Counting to the same position in the original envelope lands on a different character because the envelope has its own fields and escapes. A small synthetic reproduction with one trailing comma provides a better handoff than a screenshot of a dashboard with several additional layers of display escaping.
{"event":"label.printed","body":"{\"lines\":[\"Rack A\",]}"}{"lines":["Rack A",]}Isolate any extra layer introduced by logging
A structured logger can put the entire wire message in a string field called record. Exporting that log entry as JSON adds a third serialization. Parse the log envelope once and compare its record value with the original wire text. If they match character for character, the logger preserved the message and added an outer container for its own fields. If they differ, check for truncation, filtering, or a formatter that decoded and reserialized the event before storage.
Keep a contract example for each supported queue version. For this one, include an ordinary label, the real newline, the literal backslash, and a malformed inner array. Check the expected type at each boundary and the final printer values for the valid cases. Record which stage rejects the malformed case. This small set catches a change such as a client library starting to decode an extra layer, even when the pretty-printed logs look much the same.
For a regression test, feed the recovered wire text to the exact consumer function used by the queue client. The fixture can travel through the logger without ever contacting a queue or a printer. This preserves an inexpensive way to check a serializer upgrade and gives reviewers a definitive answer when the only visible change in a log export is an extra pair of backslashes.
const wire = JSON.stringify({ event: "label.printed", body: '{"copies":2}' });
const logLine = JSON.stringify({ level: "info", record: wire });
const recovered = JSON.parse(logLine).record;
console.log(recovered === wire); // true
console.log(JSON.parse(JSON.parse(recovered).body).copies); // 2