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

如何配置Prettier/VSCode格式化器或json2yaml消除YAML列表短横线后换行?

如何让YAML列表保持短横线后直接跟键值对的格式?

项目中要求YAML列表采用短横线后直接跟键值对的格式:

books:
  - title: "Harry Potter"
    author: "J. K. Rowling"
  - title: "Dune"
    author: "Frank Herbert"

但使用json2yaml转换JSON时,会生成短横线后换行的格式,以下是三种解决途径:

1. 使用Prettier统一格式化

Prettier可以自动调整YAML列表格式,匹配项目要求:

  • 在项目根目录创建.prettierrc配置文件,添加YAML相关规则:
# .prettierrc
yaml:
  bracketSpacing: true
  printWidth: 120
  singleQuote: false
  proseWrap: "preserve"
  • 在VSCode中设置Prettier为YAML文件的默认格式化工具:打开设置(Ctrl+,),搜索Default Formatter,将YAML的默认格式化器设为esbenp.prettier-vscode。
  • 格式化时按Ctrl+Shift+I即可自动将短横线后的换行去掉,统一为目标格式。

2. 修改json2yaml的转换参数

如果直接使用json2yaml的API或CLI工具,可以通过调整参数实现:

代码调用场景(Node.js)

const json2yaml = require('json2yaml');
const targetObj = {
  books: [
    { title: "Harry Potter", author: "J. K. Rowling" },
    { title: "Dune", author: "Frank Herbert" }
  ]
};
// 关键设置足够大的lineWidth,确保键值对能跟在短横线后
const yamlContent = json2yaml.stringify(targetObj, {
  indent: 2,
  lineWidth: 120,
  sortKeys: false // 保持原键顺序
});
console.log(yamlContent);

CLI命令行场景

json2yaml input.json --indent 2 --line-width 120 > output.yaml

通过增大line-width参数,避免列表项因宽度不足换行,从而让短横线后直接跟随键值对。

3. VSCode YAML插件(Red Hat)配置

若使用Red Hat官方的YAML插件,可直接在VSCode设置中调整格式化规则:
打开VSCode设置(Ctrl+,),添加以下配置到settings.json:

{
  "yaml.format.enable": true,
  "yaml.format.bracketSpacing": true,
  "yaml.format.printWidth": 120,
  "yaml.format.singleQuote": false
}

保存后,按Ctrl+Shift+I格式化YAML文件,即可自动修正列表格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 21:15:06