Why Does a Textarea Show Literal \\n After JSON.parse?

February 18, 2025

While building a React Flow workflow editor at PuppyAgent, I expected a text node to display the text returned by a workflow run. I remember seeing literal \n sequences where I expected line breaks. On March 3, I was also debugging unwanted quotation marks around a text node's output. The repair I committed that night explains how both symptoms can occur.12

The text moved through application code the whole way. To find where the extra characters came from, I needed to compare the event payload, the parsed field, and the value passed to the textarea.

A newline and its written representation are different things

The first question is what string reaches the editor. These two JavaScript expressions produce different runtime values:

const actualNewline = "A\nB";
const literalEscape = "A\\nB";

console.assert(actualNewline.length === 3); // A, LF, B
console.assert(literalEscape.length === 4); // A, backslash, n, B

A textarea displays the first value on two lines. With the second, it displays the backslash and n. React passes the supplied value to the textarea as text.3

On January 2, 2025, I searched for “json多行” and opened Matt Johnston's JSON with multiline strings. He compares writing a newline escape in JavaScript source with putting an actual line break in a template literal.4

Note that the output of either method is the same.

— Johnston (2023), following the template-literal example.4

const escapedSource = "Retrieve documents.\nAnswer with sources.";
const templateSource = `Retrieve documents.
Answer with sources.`;

console.assert(escapedSource === templateSource);

Johnston proposes JSONCT so people writing configuration files could also use backticks. A producer and consumer would need to agree on that syntax. With standard JSON, I can already send the same runtime string using an escaped line feed.45

A normal JSON round trip preserves the text

JSON requires control characters inside strings to be escaped. RFC 8259 includes these among the characters that must be escaped:

quotation mark, reverse solidus, and the control characters (U+0000 through U+001F).

— Bray (2017), Section 7, “Strings.”5

Seeing \n in raw JSON is therefore normal. The question is what value reaches the editor after parsing:

const original = "Retrieve documents.\nAnswer with sources.";
const wire = JSON.stringify({ content: original });
const decoded = JSON.parse(wire);

console.assert(decoded.content === original);
console.assert(decoded.content.includes("\n"));
console.assert(!decoded.content.includes("\\n"));

JSON.stringify creates a JSON representation; JSON.parse reconstructs the represented value.67 For this string, the newline survives the round trip exactly. Looking only at the wire representation can make correct encoding look like corruption.

The practical flow is:

textarea text → application string → JSON message
             → parsed application string → textarea text

Each serialization boundary needs a corresponding interpretation at the receiving side. The final textarea should receive the application string.

Where I changed the node-update logic

I went back through the early PuppyAgent code in puppyone-ai/puppyone-cloud to compare the assignment before and after my fix:

Date, UTC+8CommitChange
February 26, 2025, 22:40:381a3a2e0One node-update path changed from assigning returned content directly to applying JSON.stringify unconditionally.
March 3, 2025, 21:46:12b809a2dBoth the single-node and multiple-node update paths were changed to serialize only structured-node content.

ERerGB made the February 26 change; I committed the March 3 fix as caiborui, using my GitHub account S2thend.81 I traced this particular assignment back to the February change, but did not establish when the same pattern first appeared elsewhere in the application.

In PuppyFlow/app/components/hooks/useJsonConstructUtils.ts, I changed the assignment from:

content: JSON.stringify(item.data.content),

to:

content: (item.type ?? node.type) === "structured"
  ? JSON.stringify(item.data.content)
  : item.data.content,

These are object-property excerpts from the patch, with the new expression reformatted for readability.1 For a structured node, the editor needed a JSON representation. For ordinary text, the returned string was already the value the editor should receive.

Following the value upstream, I found that the EventSource handler already parsed event.data before passing it into the node-update logic.9 The boundary I needed to examine was the conversion from a backend result into frontend node state.

The same handler still had a commented-out parser reviver that would replace every literal backslash-plus-n in a string with a line feed. That would change legitimate text in the payload, and a reviver runs before the later node update that adds the escapes in this case. I could leave the parser alone and check how each node type uses the value it returns.19

Following it downstream led me to TextBlockNode.tsx and TextEditorTextArea. The editor initializes its local text from the node's data.content, synchronizes external content changes, and passes value={text} to a <textarea>.1011 An extra serialization step before this point would therefore reach the editor as part of its text value.

I named the commit “fix quotes outside text node when output.” I did not mention newlines in that commit message. To understand the connection to visible \n, I can reproduce what the extra JSON.stringify does to a multiline string.

What I asked Cursor that evening

I had this conversation with Cursor while debugging TextEditorTextArea.tsx on March 3. I had continued in a session called Embedding SVG in Image Source, which I started two days earlier, so the title no longer described what I was working on.

My original prompt was:

how to get rid of the quotes on the outest

— My prompt to Cursor, March 3, 2025, around 21:03.2

I had selected a line in PuppyFlow/app/components/tableComponent/TextEditorTextArea.tsx that logged getNode(parentId)?.data?.content. Cursor suggested changing the console.log formatting. That did not get to the question I needed to answer: why did the content itself have outer quotes? Changing the log format would not decode an already serialized string.

Later in the same conversation, I asked:

how to remove fisrt 2 character of a string and return the rest

— My next prompt about the quotes, around 21:29.2

At this point, I was checking whether the node's content began with a quotation mark. This was the line I selected:

console.log('text editor text set to',(getNode(parentId)?.data?.content as string).startsWith("\""))

I have only removed the leading indentation here. Cursor suggested substring(2) or slice(2). I was considering trimming the visible characters, but the fix I committed later changed how the returned content entered node state.12

March 3, 2025, UTC+8What I was doing
Around 21:03Asked Cursor about the outer quotes while inspecting the textarea's content.
Around 21:29Asked about removing two characters and checked startsWith("\"").
21:46:12Committed b809a2d, making both node-update paths serialize structured content only.

Reproducing the failure without a database

Suppose the backend has sent a valid JSON message containing multiline text. After parsing it, the frontend already has the desired string. Serializing that field again produces a different string containing JSON syntax:

const expected = "First line\nSecond line";
const message = JSON.stringify({ content: expected });
const result = JSON.parse(message);

const beforeFix = JSON.stringify(result.content);
const afterFix = result.content;

console.assert(beforeFix.startsWith('"'));
console.assert(beforeFix.includes("\\n"));
console.assert(!beforeFix.includes("\n"));
console.assert(afterFix === expected);

Assigning beforeFix to the textarea produces an outer pair of quotes and a visible \n. Assigning afterFix supplies the original multiline text. This reproduces the behavior implied by the historical patch without involving storage at all.

It also explains why a fully programmatic pipeline can fail. Serialization functions can be individually correct while being called at the wrong boundary. A transport-level parser does not help if a later UI adapter turns the decoded value back into JSON text.

My March 3 exchange records the outer quotation marks. The sample shows how that same conversion also produces visible newline escapes. The link to the earlier multiline-text incident remains uncertain.2

Other paths can produce the same visible result

One alternative is an API field containing JSON text inside an outer JSON message:

const text = "First line\nSecond line";
const nestedMessage = JSON.stringify({ content: JSON.stringify(text) });
const outer = JSON.parse(nestedMessage);

console.assert(outer.content.includes("\\n"));
console.assert(JSON.parse(outer.content) === text);

The outer parse has done its job. The inner value remains encoded because the producer explicitly made it JSON text. A second parse is appropriate only if that nested representation is part of the field's contract. Otherwise, fix the producer so the field contains ordinary text. Do not repeatedly parse arbitrary user content until it happens to look right.

A public report from ceds described almost exactly the textarea symptom:

the text is shown with the "\n" string and obviously without the real new lines

— ceds (2020), description of assigning the returned value to a textarea.12

The author later reported different behavior between server-template injection and AJAX delivery. I take that as a reminder to trace the complete data path; I would not assume our application used the same path just because the symptom looked familiar.

There are two more distinctions to retain. A debug inspector may show an escaped representation even when the runtime value contains real newlines. A database may also faithfully store a string that was already escaped before insertion. Neither observation alone identifies the component responsible. With visible backslashes inside the textarea itself, the value supplied to the editor is the first useful inspection point.

Inspect the characters at each boundary

For a small synthetic fixture, this helper distinguishes line-feed characters from literal backslash-plus-n sequences:

function inspectText(value) {
  if (typeof value !== "string") {
    return { type: typeof value };
  }

  return {
    type: "string",
    length: value.length,
    lineFeeds: (value.match(/\n/g) ?? []).length,
    literalBackslashNs: (value.match(/\\n/g) ?? []).length,
    codePoints: Array.from(value, character => character.codePointAt(0)),
  };
}

console.log(inspectText("A\nB"));   // codePoints: [65, 10, 66]
console.log(inspectText("A\\nB"));  // codePoints: [65, 92, 110, 66]

Inspect the field after response parsing, after converting the response into node state, and immediately before assigning the textarea value. If persistence is involved, compare the value passed to the database driver with the value returned by it as well. Locate the first unexpected change instead of deciding in advance that storage or rendering is responsible.

What I findWhere I look next
JSON.parse(event.data) throws.Inspect the raw event and the producer's JSON encoding. A line feed between a JSON string's quotation marks must be escaped.5
The parsed field already contains literal \n.Check whether the API promises a plain string or an encoded JSON document. Also check whether the backslash is intentional user content.
The parsed field has a real line feed, but the textarea value has outer quotes and a literal \n.Compare the parsed field with the value written into node state. In my case, JSON.stringify(item.data.content) added the quotes and replaced the line feed with an escape in updateUI and updateUIForMultipleNodes.1

The formatting tip from my separate JavaScript notes is useful here:

const readableMessage = JSON.stringify({ content: "A\nB" }, null, 2);
console.log(readableMessage);

The space argument adds indentation between JSON members.6 It does not turn JSON string escapes into textarea line breaks. Use this output to inspect message structure, and inspect the decoded field separately when checking text content.

Keep text and JSON-editor values separate

In my fix, I made the distinction based on node type. If I extracted that rule into a small adapter now, I would also reject unexpected text values:

function toEditorValue(nodeType, content) {
  if (nodeType === "structured") {
    const serialized = JSON.stringify(content, null, 2);
    if (serialized === undefined) {
      throw new TypeError("Structured content must be JSON-serializable");
    }
    return serialized;
  }

  if (typeof content !== "string") {
    throw new TypeError("Text content must be a string");
  }
  return content;
}

I wrote this adapter for the note; it is not the exact production implementation. I am assuming that structured content has already been decoded to a JSON-compatible value. If the API returns a serialized JSON document instead, I would make that contract explicit and decode it at the designated boundary.

For ordinary text, keep the runtime string in editor state and use the normal API serializer for transport. For structured data, convert between the editor's JSON document and the application's structured value at deliberate points. Validate against the expected schema separately; being serializable does not establish that a value has the correct shape.

Avoid a blanket replacement of \\n with a newline. A prompt, code sample, regular expression, or path can legitimately contain those two characters. Similarly, adding <br> does not solve a textarea value problem: the control displays text rather than interpreting HTML markup. If old data is known to use an extra encoding layer, decode it through an explicit, versioned migration or compatibility path.

For regression coverage, I would include a multiline text result, quotes and backslashes, intentional literal \n, empty text, Unicode text, and structured content containing a multiline field. I would check both single-node and multiple-node result handling, since I changed both paths. I would also test saving and reloading wherever the application promises that round trip, accounting for any intended CRLF/LF normalization at the browser boundary.

What I want to remember from this debugging is where the conversion belongs. Once I have ordinary text, I should keep it as text in editor state. Serializing it for transport and formatting a JSON document for an editor are separate operations.

References

Footnotes

  1. caiborui [S2thend]. (2025, March 3). Fix quotes outside text node when output [Commit b809a2d]. GitHub, puppyone-ai/puppyone-cloud. Changes to updateUI and updateUIForMultipleNodes. https://github.com/puppyone-ai/puppyone-cloud/commit/b809a2daf392ff5e27f7b3339b0506310fd49a0b ↩ ↩2 ↩3 ↩4 ↩5 ↩6

  2. CaiBorui & Cursor. (2025, March 3). Embedding SVG in Image Source: Later textarea quotation-mark debugging [Local conversation excerpt]. Cursor. Session 947323e1-9392-4a12-abaf-169557fff95d, original messages 13–16 and attached selections from TextEditorTextArea.tsx; the session itself was created March 1. Times are the assistant messages' timingInfo.clientStartTime, not independently stored user-message timestamps. Archived original wording and selected code. Verified November 16, 2026, by read-only access to the legacy inline conversation in composerData:<session-id>. ↩ ↩2 ↩3 ↩4 ↩5

  3. React. (n.d.). textarea. “Reference” and “Controlling a text area with a state variable.” https://react.dev/reference/react-dom/components/textarea ↩

  4. Johnston, M. (2023, May 22). JSON with multiline strings [Blog post, originally published May 19, 2023]. DEV Community, Polyseam. Quotation from the paragraph immediately following the template-literal example. https://dev.to/polyseam/json-with-multiline-strings-4645 ↩ ↩2 ↩3

  5. Bray, T. (Ed.). (2017, December). The JavaScript Object Notation (JSON) data interchange format (RFC 8259). Section 7, “Strings.” RFC Editor. https://www.rfc-editor.org/rfc/rfc8259.html#section-7 ↩ ↩2 ↩3

  6. MDN contributors. (n.d.). JSON.stringify(). “Parameters” and “Using the space parameter.” https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify ↩ ↩2

  7. MDN contributors. (n.d.). JSON.parse(). https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse ↩

  8. ERerGB. (2025, February 26). Stringify content in JSON node construction to ensure valid JSON [Commit 1a3a2e0]. GitHub, puppyone-ai/puppyone-cloud. https://github.com/puppyone-ai/puppyone-cloud/commit/1a3a2e03f3c711fa1de65f790e54cfee168e8245 ↩

  9. PuppyAgent contributors. (2025, March 3). useJsonConstructUtils.ts [Source code at commit b809a2d]. GitHub, puppyone-ai/puppyone-cloud. EventSource handler, commented-out reviver, and call to update the nodes. https://github.com/puppyone-ai/puppyone-cloud/blob/b809a2daf392ff5e27f7b3339b0506310fd49a0b/PuppyFlow/app/components/hooks/useJsonConstructUtils.ts#L273-L341 ↩ ↩2

  10. PuppyAgent contributors. (2025, March 3). TextBlockNode.tsx [Source code at commit b809a2d]. GitHub, puppyone-ai/puppyone-cloud. Plain-text editor composition. https://github.com/puppyone-ai/puppyone-cloud/blob/b809a2daf392ff5e27f7b3339b0506310fd49a0b/PuppyFlow/app/components/workflow/blockNode/TextBlockNode.tsx#L434 ↩

  11. PuppyAgent contributors. (2025, March 3). TextEditorTextArea.tsx [Source code at commit b809a2d]. GitHub, puppyone-ai/puppyone-cloud. State initialization, synchronization, and textarea value. https://github.com/puppyone-ai/puppyone-cloud/blob/b809a2daf392ff5e27f7b3339b0506310fd49a0b/PuppyFlow/app/components/tableComponent/TextEditorTextArea.tsx#L24 ↩

  12. ceds. (2020, May 28). Javascript JSON.stringify text with \n not showing Javascript string with new line [Question and author's follow-up answer]. Stack Overflow. Quotation from the paragraph describing the textarea assignment. https://stackoverflow.com/questions/62059578/javascript-json-stringify-text-with-n-not-showing-javascript-string-with-new-l ↩

© 2025 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2025-02-18). Why Does a Textarea Show Literal \\n After JSON.parse?. https://caiborui.com/blog/2025-02-18-en-json-newlines-in-workflow-textareas

@misc{borui2025-3bfb5f0d,
  author = {borui},
  title = {{Why Does a Textarea Show Literal \\n After JSON.parse?}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-02-18-en-json-newlines-in-workflow-textareas}
}