You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在YAML中定义多行字符串并确保产品端保留换行?

YAML多行字符串转JSON后换行丢失的解决办法

问题根源

你用YAML的|块标量写的多行字符串,在编辑器和Crowdin里显示正常,但转JSON后产品输出换行没了——本质是YAML转JSON的工具没保留换行符,或者渲染层没解析这些换行。YAML的|确实会保留换行,但转成JSON时,这些换行需要变成\n才算有效,很多转换工具默认可能会把换行合并成空格。

可行解决方案

1. 调整YAML转JSON工具的配置,强制保留\n

不同工具的配置不一样,举两个常用的例子:

  • js-yaml:转换时加上{ lineWidth: -1, preserveQuotes: true }参数,避免工具自动压缩换行。
  • PyYAML:加载YAML用yaml.load(file, Loader=yaml.FullLoader),转JSON时用json.dump(data, file, ensure_ascii=False),确保块标量的换行被转成\n。

转完后的JSON应该是这个样子:

{
  "landing": {
    "description": "We invite you to take 20 minutes to complete this form.\nWhat is it for? Your answers will allow us to get to know you.\nNote: There are no right or wrong answers."
  }
}

2. 直接在YAML里写\n显式换行

如果转换工具没法改配置,就放弃|,用双引号把字符串包起来,直接写\n:

landing:
  description: "We invite you to take 20 minutes to complete this form.\nWhat is it for? Your answers will allow us to get to know you.\nNote: There are no right or wrong answers."

这样转JSON后\n会被保留,只要渲染层正确处理就能显示换行。

3. 用<br/>(仅限Web场景)

如果你的产品是Web应用,且前端支持渲染HTML,直接在YAML里加<br/>就行:

landing:
  description: |
    We invite you to take 20 minutes to complete this form.<br/>
    What is it for? Your answers will allow us to get to know you.<br/>
    Note: There are no right or wrong answers.

但注意:原生APP或纯文本场景不能用这个,会直接显示<br/>字符。

验证步骤

  1. 先看转换后的JSON文件,确认字符串里有\n或者<br/>;
  2. 再检查渲染代码:Web端要把\n替换成<br/>(比如用str.replace(/\n/g, '<br/>')),原生APP要设置文本支持多行显示。

内容的提问来源于stack exchange,提问作者Luciano Cipolla

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 02:17:25