什么是 YAML 转 JSON 转换?
YAML 转 JSON 转换是将 YAML(YAML Ain't Markup Language)格式的数据转换为 JSON(JavaScript Object Notation)格式的过程。两种格式均以键值对、序列和嵌套对象表示结构化数据,但语法不同。YAML 使用缩进和简洁的标点符号,而 JSON 使用花括号、方括号和强制引号。当需要在不同系统之间传递配置数据时,二者之间的转换是一项常见任务。
YAML 专为人类可读性而设计,支持注释、多行字符串、锚点和别名——而这些特性在 JSON 中均不存在。将 YAML 转换为 JSON 时,这些 YAML 特有功能会被解析处理:锚点被内联展开,注释被丢弃,多行块变为转义字符串。输出结果是任何 JSON 解析器都能读取的有效 JSON。
YAML 1.2 规范明确将 JSON 定义为 YAML 的子集,即每个有效的 JSON 文档同时也是有效的 YAML。反之则不然。使用注释、锚点或复杂键的 YAML 文档没有直接对应的 JSON 形式,转换时必须进行简化处理。本工具可自动完成该转换,将任何有效的 YAML 输入转换为格式规范的 JSON。
YAML 1.2 Specification — yaml.org →
为什么使用在线 YAML 转 JSON 转换器?
手动将 YAML 转换为 JSON 容易出错,尤其是面对深层嵌套结构或多行值时。基于浏览器的转换器能即时给出结果,并在 YAML 语法错误进入应用程序之前将其捕获。
YAML 转 JSON 使用场景
YAML 转 JSON 类型映射参考
每种 YAML 数据类型在转换过程中都映射到特定的 JSON 类型。下表列出了各 YAML 构造及其对应的 JSON 输出。了解这些映射关系有助于预测 YAML 数据转换后的形态,避免布尔值或 null 值等类型出现意外结果。
| YAML 类型 | YAML 语法 | JSON 输出 |
|---|---|---|
| Mapping | name: Alice | { "name": "Alice" } |
| Sequence | - apple\n- banana | ["apple", "banana"] |
| String | greeting: hello world | "hello world" |
| Integer | count: 42 | 42 |
| Float | ratio: 3.14 | 3.14 |
| Boolean | active: true | true |
| Null | value: null | null |
| Multiline (|) | bio: |\n Line one\n Line two | "Line one\nLine two\n" |
| Folded (>) | note: >\n A long\n paragraph | "A long paragraph\n" |
| Anchor/Alias | &default\n <<: *default | Resolved inline (no $ref) |
YAML 与 JSON 语法对比
YAML 和 JSON 表示相同的数据模型,但语法规则不同。以下差异解释了为何注释、锚点等 YAML 特性在 JSON 中没有等价形式。
代码示例
以下是以编程方式将 YAML 转换为 JSON 的示例。每个示例均解析一个 YAML 字符串并输出格式化的 JSON。
import { load } from 'js-yaml'
const yamlStr = `
server:
host: localhost
port: 8080
ssl: true
`
const json = JSON.stringify(load(yamlStr), null, 2)
console.log(json)
// → {
// → "server": {
// → "host": "localhost",
// → "port": 8080,
// → "ssl": true
// → }
// → }import yaml, json
yaml_str = """
database:
host: db.example.com
port: 5432
credentials:
user: admin
password: s3cret
"""
data = yaml.safe_load(yaml_str)
print(json.dumps(data, indent=2))
# → {
# → "database": {
# → "host": "db.example.com",
# → "port": 5432,
# → "credentials": {
# → "user": "admin",
# → "password": "s3cret"
# → }
# → }
# → }package main
import (
"encoding/json"
"fmt"
"log"
"gopkg.in/yaml.v3"
)
func main() {
yamlData := []byte(`
services:
web:
image: nginx:latest
ports:
- "80:80"
`)
var obj map[string]interface{}
if err := yaml.Unmarshal(yamlData, &obj); err != nil {
log.Fatal(err)
}
jsonBytes, _ := json.MarshalIndent(obj, "", " ")
fmt.Println(string(jsonBytes))
// → { "services": { "web": { "image": "nginx:latest", "ports": ["80:80"] } } }
}# Convert a YAML file to JSON with yq
yq -o=json config.yaml > config.json
# Pipe YAML into yq for one-off conversion
echo "name: demo" | yq -o=json
# → { "name": "demo" }
# Python one-liner (no extra install on most systems)
python3 -c "import yaml, json, sys; print(json.dumps(yaml.safe_load(sys.stdin), indent=2))" < config.yaml