Skip to main content
On this page

@std/yaml

Overview Jump to heading

parse and stringify for handling YAML encoded data.

Ported from js-yaml v3.13.1.

Use parseAll for parsing multiple documents in a single YAML string.

This package generally supports YAML 1.2.x (latest) and some YAML 1.1 features that are commonly used in the wild.

Supported YAML 1.1 features include:

Unsupported YAML 1.1 features include:

  • Yes, No, On, Off literals for bool type
  • Sexagesimal numbers (e.g. 3:25:45)
import { parse, stringify } from "@std/yaml";
import { assertEquals } from "@std/assert";

const data = parse(`
foo: bar
baz:
  - qux
  - quux
`);
assertEquals(data, { foo: "bar", baz: [ "qux", "quux" ] });

const yaml = stringify({ foo: "bar", baz: ["qux", "quux"] });
assertEquals(yaml, `foo: bar
baz:
  - qux
  - quux
`);

Limitations

  • binary type is currently not stable.

Add to your project Jump to heading

deno add jsr:@std/yaml

See all symbols in @std/yaml on

什么是 YAML? Jump to heading

YAML(YAML 不是标记语言)是一种易于人类阅读的数据序列化格式, 通常用于配置文件和不同语言之间的数据交换。 它强调简单性和可读性,使人类易于编写和理解。

为什么使用 @std/yaml? Jump to heading

YAML 非常适合优先考虑人类可读性的配置文件和数据交换场景。 当你需要以一种便于人类阅读和编辑的方式表示复杂数据结构时,使用它。 该模块提供了简单的函数来解析和序列化 YAML 数据。

示例 Jump to heading

读取配置文件(带错误处理) Jump to heading

import { parse } from "@std/yaml";

const raw = await Deno.readTextFile("config.yaml");
let config;
try {
  config = parse(raw);
} catch (err) {
  if (err instanceof SyntaxError) {
    console.error("无效的 YAML:", err.message);
  }
  throw err;
}

// 在使用前根据需要进行类型缩小/校验
if (
  typeof config === "object" && config !== null &&
  "port" in config && typeof config.port === "number"
) {
  console.log("监听端口", config.port);
}

一个文件中的多个文档 Jump to heading

import { parseAll } from "@std/yaml";

const docs = parseAll(`
---
name: dev
port: 3000
---
name: prod
port: 80
`);

// 例如,将环境名映射到端口号
const envToPort = Object.fromEntries(docs.map((d) => [d.name, d.port]));
console.log(envToPort.dev, envToPort.prod);

生成稳定的 YAML 差异(排序键,换行) Jump to heading

import { stringify } from "@std/yaml";

const data = {
  name: "service",
  description: "演示长行如何换行的示例。",
  tags: ["alpha", "beta", "gamma"],
  nested: { z: 1, a: 2, m: 3 },
};

const yaml = stringify(data, { sortKeys: true, lineWidth: 60, indent: 2 });
console.log(yaml);

YAML 锚点与合并键(YAML 1.1) Jump to heading

import { parse } from "@std/yaml";

const cfg = parse(`
defaults: &base
  retries: 3
  timeout: 5s

serviceA:
  <<: *base
  timeout: 10s

serviceB:
  <<: *base
`);

console.log(cfg.serviceA.timeout); // "10s"
console.log(cfg.serviceB.retries); // 3

序列化时跳过不支持的值 Jump to heading

import { stringify } from "@std/yaml";

const obj = { ok: 1, skipMe: () => {} };
// 默认情况下,函数会导致 TypeError。使用 skipInvalid 选项可以忽略它们。
const yaml = stringify(obj, { skipInvalid: true });
console.log(yaml);

将 YAML 写回磁盘 Jump to heading

import { stringify } from "@std/yaml";

const settings = { port: 8080, features: { a: true, b: false } };
await Deno.writeTextFile("settings.yaml", stringify(settings, { indent: 2 }));

使用技巧 Jump to heading

  • 如果预期一个字符串中有多个 YAML 文档,请使用 parseAll
  • 推荐在机器间互换使用 JSON;YAML 非常适合手工编辑的配置文件。
  • 为了在版本控制系统中获得稳定的差异,使用 stringify 时请设置 sortKeys: true 并固定 indentlineWidth

你找到了你需要的东西吗?

编辑此页面
隐私政策