为什么 JSON.parse 之后,文本框里还会出现字面量 \\n?

February 18, 2025

在 PuppyAgent 开发 React Flow 工作流编辑器时,我希望文本节点直接显示工作流运行后返回的文字。我记得,本该换行的位置显示了字面量 \n。3 月 3 日,我还在排查文本节点输出外围多出引号的问题。当晚提交的修复解释了这两种现象是怎样产生的。12

文本从头到尾都由应用代码传递。要找到多余字符从哪里来,我需要比较事件载荷、解析后的字段,以及传给文本框的值。

换行符和写出换行符的方式是两回事

首先要看编辑器收到的究竟是什么字符串。下面两条 JavaScript 表达式的运行时值不同。

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

文本框会把第一个值显示为两行,而对于第二个值,会把反斜杠和 n 显示出来。React 把传入的 value 作为文字交给 textarea。3

2025 年 1 月 2 日,我搜索“json多行”,读到 Matt Johnston 的《JSON with multiline strings》。他比较了两种写法:在 JavaScript 源码中写换行转义,以及在模板字面量里直接换行。4

Note that the output of either method is the same.

注意,这两种写法的输出相同。——Johnston(2023),模板字面量示例之后。4

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

console.assert(escapedSource === templateSource);

Johnston 提出 JSONCT,让手写配置文件的人也能使用反引号。这需要生产者和消费者就语法达成一致。使用标准 JSON,只需对换行符进行转义,就能发送同一个运行时字符串。45

正常的 JSON 往返会保留文本

JSON 要求字符串里的控制字符必须转义。RFC 8259 把以下字符列为必须转义的字符:

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

引号、反斜杠和控制字符(U+0000 至 U+001F)。——Bray(2017),第 7 节“字符串”。5

所以在原始 JSON 中看见 \n 是正常的。问题是解析之后编辑器收到什么值。

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 产生值的 JSON 表示,JSON.parse 则从中还原该值。67 对于这个字符串,换行符往返后原样保留。只看传输中的表示,可能会把正常编码误认成数据损坏。

实际流程如下。

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

每次跨过序列化边界,接收方都要按相应的方式解释数据。最终传入 textarea 的应该是应用中的字符串。

我在哪里改了节点更新逻辑

我回头翻查 puppyone-ai/puppyone-cloud 中 PuppyAgent 的早期代码,对比修复前后的赋值逻辑。

日期,UTC+8提交变更
2025 年 2 月 26 日 22:40:381a3a2e0一条更新节点的路径原先直接赋返回内容,改成了无条件调用 JSON.stringify。
2025 年 3 月 3 日 21:46:12b809a2d单节点和多节点更新路径都改为只序列化结构化节点的内容。

2 月 26 日的变更由 ERerGB 提交,3 月 3 日的修复由我以 caiborui 的身份、使用我的 GitHub 账号 S2thend 提交。81 我把这处具体的赋值追溯到 2 月的变更,至于应用的其他地方最早什么时候出现同样的写法,当时没有查清。

在 PuppyFlow/app/components/hooks/useJsonConstructUtils.ts 中,我把以下赋值:

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

改成了:

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

这两段是补丁中的对象属性,新表达式为了便于阅读重新排了版。1 对结构化节点,编辑器需要 JSON 表示。对普通文本,返回的字符串已经是编辑器应该收到的值。

我往上游追踪,发现 EventSource 处理函数在把 event.data 传给节点更新逻辑之前已经做了解析。9 需要检查的是后端结果转成前端节点状态的边界。

同一个处理函数里还有一段注释掉的解析器 reviver,它会把字符串中每个字面上的反斜杠加 n 替换为换行符。这样做会改动载荷里的合法文本,而且 reviver 的执行早于本例中添加转义的节点更新。我可以保留解析器,去检查各类节点如何使用它返回的值。19

沿下游查找,我来到 TextBlockNode.tsx 和 TextEditorTextArea。编辑器用节点的 data.content 初始化本地文本,同步外部内容的变化,再把 value={text} 传给 <textarea>。1011 因此,只要在这一步之前多做一次序列化,多出的字符就会成为编辑器文本的一部分。

我给提交起名叫“fix quotes outside text node when output”,没有在提交说明中提及换行。要了解它和可见的 \n 有什么关系,可以复现额外调用 JSON.stringify 对多行字符串产生的效果。

那天晚上我问了 Cursor 什么

3 月 3 日调试 TextEditorTextArea.tsx 时,我和 Cursor 有过下面这段对话。我沿用了两天前创建的会话 Embedding SVG in Image Source,所以标题已经不能反映当时在做什么。

我最初的问题是:

how to get rid of the quotes on the outest

怎样去掉最外层的引号?——我在 2025 年 3 月 3 日约 21:03 给 Cursor 的提示。2

我在 PuppyFlow/app/components/tableComponent/TextEditorTextArea.tsx 里选中了打印 getNode(parentId)?.data?.content 的一行。Cursor 建议修改 console.log 的输出格式。这没有回答我真正要弄清的问题:内容本身为什么会有外层引号?改日志格式无法解码已经序列化的字符串。

同一段对话里,我后来又问:

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

怎么删除字符串的前两个字符并返回剩余部分?——约 21:29,我就引号问题接着问。2

当时我在检查节点内容是否以引号开头,选中的是下面这行。

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

这里只删去了行首缩进。Cursor 建议使用 substring(2) 或 slice(2)。我当时在考虑裁掉看得见的字符,但稍后提交的修复改的是返回内容进入节点状态的方式。12

2025 年 3 月 3 日,UTC+8我在做什么
约 21:03检查文本框的内容,向 Cursor 询问外层引号。
约 21:29询问如何移除两个字符,并检查 startsWith("\"")。
21:46:12提交 b809a2d,让两条更新路径都只序列化结构化内容。

不用数据库也能复现

假设后端发送了一条有效的 JSON 消息,其中有多行文本。解析之后,前端已经拿到了想要的字符串。再次序列化该字段,得到的则是另一个包含 JSON 语法的字符串。

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);

把 beforeFix 赋给 textarea,外层会多出一对引号,还会显示 \n。赋 afterFix 则能传入原来的多行文本。这就复现了历史补丁所反映的行为,全程无须涉及存储。

这也解释了为什么完全由程序处理的链路也会出错。序列化函数本身可以都正确,却在错误的边界被调用。如果之后的 UI 适配器把已解码的值重新变成 JSON 文本,传输层的解析器就帮不上忙。

3 月 3 日的对话记录了外层引号。示例表明同一次转换也会产生可见的换行转义。它和较早那次多行文本问题之间的关系仍不能确定。2

其他路径也可能产生同样的结果

另一种情况是,外层 JSON 消息中的一个 API 字段本身存放了 JSON 文本。

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);

外层解析已经完成了自己的工作。内层依旧处于编码状态,是因为生产者显式把它做成了 JSON 文本。只有字段契约规定了这种嵌套表示,第二次解析才合理。否则应修改生产方,让该字段包含普通文本。不要反复解析任意用户内容,直到碰巧看上去正确。

ceds 的一则公开提问描述了几乎一模一样的文本框现象:

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

文本中显示的是“\n”这个字符串,显然也没有真正换行。——ceds(2020),描述把返回值赋给 textarea 时的情况。12

作者后来报告,服务端模板注入和 AJAX 交付的表现不同。对我来说,这是追踪完整数据路径的提醒。症状相似,不能证明我们的应用经过了同样的路径。

还要区分两种情况。调试器可能显示转义后的表示,而运行时值里有真正的换行符。数据库也可能忠实保存一个在写入前就已转义的字符串。单凭其中任一现象,都无法找出负责的组件。如果反斜杠出现在文本框里,先检查传给编辑器的值。

在每个边界检查字符

对一个小型测试样例,下面的辅助函数可以区分换行符和字面量反斜杠加 n。

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]

分别在响应解析后、响应转为节点状态后、将值赋给 textarea 之前检查字段。如果涉及持久化,也比较传给数据库驱动的值和驱动返回的值。找出首次发生意外变化的位置,避免预先认定是存储或渲染造成的。

我发现的现象接下来检查哪里
JSON.parse(event.data) 抛出异常。检查原始事件和生产方的 JSON 编码。JSON 字符串引号之间的换行符必须转义。5
解析后的字段已经含有字面量 \n。检查 API 约定的是普通字符串还是编码后的 JSON 文档,并确认反斜杠是否为用户有意输入的内容。
解析后的字段含有真正的换行符,文本框值却有外层引号和字面量 \n。比较解析后的字段与写入节点状态的值。在我的案例中,updateUI 和 updateUIForMultipleNodes 里的 JSON.stringify(item.data.content) 添加了引号,并把换行符替换成转义序列。1

我另一本 JavaScript 笔记里的格式化技巧在这里也有用。

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

space 参数在 JSON 成员之间添加缩进。6 它不会把 JSON 字符串中的转义变成文本框换行。用这种输出检查消息结构,检查文本内容时则单独查看解码后的字段。

区分文本和 JSON 编辑器使用的值

修复时,我按节点类型做了区分。如果现在把这条规则抽成一个小适配器,我还会拒绝意外的文本值。

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;
}

这个适配器是为笔记写的,与生产环境中的具体实现不完全相同。我假定结构化内容已经解码成兼容 JSON 的值。如果 API 返回的是序列化的 JSON 文档,我会明确写出这个契约,并在指定的边界解码。

普通文本应该以运行时字符串的形式保存在编辑器状态中,由常规 API 序列化器负责传输。结构化数据则应在明确的位置让编辑器的 JSON 文档与应用中的结构化值互相转换。另行根据预期模式校验数据,能被序列化并不证明其形状正确。

避免把所有 \\n 一律替换成换行。提示词、代码示例、正则表达式和路径都可能合法地包含这两个字符。同理,加 <br> 也解决不了 textarea 的值问题,因为控件会显示文字,不会解释 HTML 标记。如果已知旧数据多了一层编码,可以用明确、带版本的迁移或兼容路径解码。

回归测试里,我会放入多行文本结果、引号和反斜杠、有意保留的字面量 \n、空文本、Unicode 文本,以及含有多行字段的结构化内容。单节点和多节点结果处理都要检查,因为两条路径我都改了。在应用承诺支持保存再加载的位置,我还会测试这次往返,并考虑浏览器边界上有意进行的 CRLF/LF 规范化。

这次调试我想记住的是转换应该发生在哪里。一旦拿到了普通文本,就把它作为文本保存在编辑器状态中。为传输而序列化,和为编辑器而格式化 JSON 文档,是两次不同的操作。

参考资料

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). 为什么 JSON.parse 之后,文本框里还会出现字面量 \\n?. https://caiborui.com/blog/2025-02-18-en-json-newlines-in-workflow-textareas-zhtrans

@misc{borui2025-0bbca10b,
  author = {borui},
  title = {{为什么 JSON.parse 之后,文本框里还会出现字面量 \\n?}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-02-18-en-json-newlines-in-workflow-textareas-zhtrans}
}