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

如何去除eemeli/yaml解析器输出中Docker Compose服务前的问号?

解决eemeli/yaml生成Docker Compose时服务名前出现问号的问题

问题重现

使用eemeli/yaml解析器生成或更新Docker Compose文件时,添加新服务my-service后,输出的YAML文件中该服务名前会出现问号,相关示例如下:

原有Docker Compose模板

version: '3.8'
services:
  web:
    image: nginx:alpine
    ports:
      - 80:80

操作代码

import yaml from 'eemeli/yaml'

// 加载原有模板为JS对象
const composeConfig = yaml.parse(/* 原有模板内容 */)

// 添加新服务
composeConfig.services['my-service'] = {
  image: 'my-image:latest',
  restart: 'always'
}

// 生成YAML输出
const output = yaml.stringify(composeConfig)
console.log(output)

异常输出

version: 3.8
services:
  web:
    image: nginx:alpine
    ports:
      - 80:80
  ? my-service
  : image: my-image:latest
    restart: always

原因分析

eemeli/yaml默认会对可能存在解析歧义的键启用显式映射键语法(?开头),即使my-service这类含连字符的键本身没有歧义,库的默认规则也可能触发该行为,导致服务名被特殊标记。

解决方案

在调用yaml.stringify()时添加explicitKeys: false配置,强制关闭显式键生成,同时可配合quotingType: ''确保键名不被多余引号包裹:

const output = yaml.stringify(composeConfig, {
  explicitKeys: false,
  quotingType: ''
})

验证结果

调整后输出的Docker Compose内容恢复正常:

version: 3.8
services:
  web:
    image: nginx:alpine
    ports:
      - 80:80
  my-service:
    image: my-image:latest
    restart: always

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 12:52:41