什么是JSON转YAML转换?
JSON转YAML转换是将JavaScript Object Notation格式的数据转换为YAML Ain't Markup Language格式的过程。两种格式表示相同的数据结构(对象、数组、字符串、数字、布尔值、null),但语法不同。JSON依赖花括号、方括号和逗号,而YAML使用缩进和换行符,生成的输出更接近纯文本。与XML不同,这两种格式都不需要schema。
YAML被设计为对人友好的数据序列化格式,是Kubernetes清单、Docker Compose文件、Ansible playbook、GitHub Actions工作流及众多CI/CD系统的默认配置语言。当源数据为JSON而目标系统需要YAML时,你需要一个能够无损保留每个值、类型和嵌套层级的转换工具。
当你收到JSON格式的API响应或导出数据,需要将其粘贴到YAML配置文件时,在线JSON转YAML转换非常实用。转换对所有标准JSON类型都是无损的:字符串、数字、布尔值、null、数组和对象都可以直接映射到对应的YAML格式。包含冒号或特殊字符的值会自动加引号,确保输出的YAML有效。
RFC 8259 — The JSON Data Interchange Standard →YAML 1.2 Specification — yaml.org →
为什么要将JSON转换为YAML?
YAML是配置文件的标准格式,而JSON是API返回数据的格式。在二者之间转换,让你无需手动改写数据,就能为每项任务选择合适的格式。
JSON转YAML使用场景
JSON与YAML对比
JSON和YAML可以表示相同的数据,但其语法和功能在特定使用场景下存在重要差异。
| 特性 | JSON | YAML |
|---|---|---|
| Syntax | Curly braces, square brackets, colons, commas | Indentation-based, colons, dashes |
| Readability | Moderate — nested brackets become dense | High — visual hierarchy from indentation |
| Comments | Not allowed (RFC 8259) | Supported with # |
| Multi-line strings | Escape sequences only (\n) | Block scalars with | or > |
| Data types | string, number, boolean, null, object, array | Same plus date, timestamp, binary |
| File size | Slightly larger (brackets + quotes) | Slightly smaller (no brackets) |
| Trailing commas | Not allowed | Not applicable (no commas) |
| Spec | RFC 8259 / ECMA-404 | YAML 1.2 (yaml.org) |
转换后的YAML注意事项
YAML有一些来自JSON背景的开发者容易忽视的解析规则。以下四个问题是使用转换输出时最常见的bug来源。
代码示例
在大多数编程语言中,以编程方式将JSON转换为YAML需要一个YAML序列化库。标准库负责JSON解析,YAML输出则需要额外的第三方包。
import YAML from 'js-yaml'
const json = '{"host":"localhost","port":3000,"debug":true}'
const obj = JSON.parse(json)
const yamlStr = YAML.dump(obj, { indent: 2 })
console.log(yamlStr)
// → host: localhost
// → port: 3000
// → debug: trueimport json, yaml
json_str = '{"host": "localhost", "port": 3000, "debug": true}'
data = json.loads(json_str)
yaml_str = yaml.dump(data, default_flow_style=False, sort_keys=False)
print(yaml_str)
# → host: localhost
# → port: 3000
# → debug: truepackage main
import (
"encoding/json"
"fmt"
"gopkg.in/yaml.v3"
)
func main() {
jsonStr := `{"host":"localhost","port":3000,"debug":true}`
var data map[string]interface{}
json.Unmarshal([]byte(jsonStr), &data)
yamlBytes, _ := yaml.Marshal(data)
fmt.Println(string(yamlBytes))
// → debug: true
// → host: localhost
// → port: 3000
}# Using yq (https://github.com/mikefarah/yq)
echo '{"host":"localhost","port":3000}' | yq -P
# → host: localhost
# → port: 3000
# Using Python one-liner
echo '{"host":"localhost","port":3000}' | python3 -c "import sys,json,yaml; print(yaml.dump(json.load(sys.stdin), default_flow_style=False))"