Die YAML-zu-JSON-Konvertierung ist eine der haufigsten Datenformataufgaben fur Entwickler. Ob Sie Kubernetes-Manifeste, Docker-Compose-Dateien oder CI/CD-Pipelines verwalten – Sie mussen haufig zwischen YAML und JSON konvertieren. Dieser umfassende Leitfaden behandelt Konvertierungstools, den Parsing-Prozess, Codebeispiele und Best Practices.
Testen Sie unseren kostenlosen Online YAML-zu-JSON / JSON-zu-YAML-Konverter.
Was ist YAML?
YAML (YAML Ain't Markup Language) ist eine menschenfreundliche Datenserialisierungssprache, die haufig fur Konfigurationsdateien verwendet wird. Ein YAML-Parser liest die einruckungsbasierte Struktur und konvertiert sie in native Datenstrukturen.
YAML verwendet Leerzeichen-Einruckung (niemals Tabs) zur Strukturierung. Es unterstutzt skalare Typen, Sequenzen (Arrays) und Mappings (Dictionaries). Erweiterte Funktionen umfassen Anker und Aliase, mehrzeilige Strings und Mehrfachdokumente getrennt durch ---. YAML ist ein Superset von JSON.
YAML ist das bevorzugte Format fur Kubernetes, Ansible, Docker Compose, GitHub Actions und viele andere Cloud-native Tools. Seine Lesbarkeit macht es ideal fur von Menschen bearbeitete Dateien.
YAML vs JSON: Wesentliche Unterschiede
Das Verstandnis der Unterschiede hilft bei der Formatwahl:
| Merkmal | YAML | JSON |
|---|---|---|
| Syntax | Einruckungsbasiert | Klammer-basiert |
| Kommentare | Ja mit # | Nein |
| Datentypen | Strings, Zahlen, Booleans, null, Datum | Strings, Zahlen, Booleans, null, Arrays, Objekte |
| Lesbarkeit | Sehr gut lesbar | Ausfuhrlicher |
| Geschwindigkeit | Langsamer | Schneller |
Wie YAML-zu-JSON-Konvertierung funktioniert
Ein YAML-zu-JSON-Konverter fuhrt einen mehrstufigen Parsing- und Serialisierungsprozess durch.
Schritt 1: Lexikalische Analyse — Der YAML-Parser identifiziert Token: Einruckungsebenen, Trennzeichen, Blockindikatoren.
Schritt 2: AST-Konstruktion — Token werden zu einem abstrakten Syntaxbaum zusammengesetzt.
Schritt 3: Native Datenstrukturen — Der AST wird in native Sprachstrukturen mit Typauflosung konvertiert.
Schritt 4: JSON-Serialisierung — Die Strukturen werden als JSON serialisiert. YAML-Kommentare werden verworfen.
YAML-zu-JSON Codebeispiele
JavaScript / Node.js (js-yaml)
Die js-yaml-Bibliothek ist der beliebteste YAML-Parser fur JavaScript:
// ===== YAML to JSON (Node.js) =====
const yaml = require('js-yaml');
const fs = require('fs');
// Parse YAML string to JavaScript object
const yamlString = `
server:
host: localhost
port: 8080
ssl: true
database:
name: myapp
replicas:
- host: db1.example.com
port: 5432
- host: db2.example.com
port: 5432
# Connection pool settings
pool:
min: 5
max: 20
`;
const data = yaml.load(yamlString);
const json = JSON.stringify(data, null, 2);
console.log(json);
// {
// "server": {
// "host": "localhost",
// "port": 8080,
// "ssl": true
// },
// "database": {
// "name": "myapp",
// "replicas": [
// { "host": "db1.example.com", "port": 5432 },
// { "host": "db2.example.com", "port": 5432 }
// ],
// "pool": { "min": 5, "max": 20 }
// }
// }
// ===== JSON to YAML =====
const jsonData = { name: 'app', version: '2.0', features: ['auth', 'logging'] };
const yamlOutput = yaml.dump(jsonData, { indent: 2 });
console.log(yamlOutput);
// name: app
// version: '2.0'
// features:
// - auth
// - logging
// ===== Read YAML file and convert to JSON =====
const fileContent = fs.readFileSync('config.yaml', 'utf8');
const config = yaml.load(fileContent);
fs.writeFileSync('config.json', JSON.stringify(config, null, 2));
// ===== Handle multi-document YAML =====
const multiDoc = `
---
name: doc1
---
name: doc2
`;
const docs = yaml.loadAll(multiDoc);
console.log(JSON.stringify(docs, null, 2));
// [{ "name": "doc1" }, { "name": "doc2" }]Python (PyYAML)
Verwenden Sie immer yaml.safe_load() um beliebige Codeausfuhrung zu verhindern:
import yaml
import json
# ===== YAML to JSON =====
yaml_string = """
server:
host: localhost
port: 8080
ssl: true
database:
name: myapp
replicas:
- host: db1.example.com
port: 5432
- host: db2.example.com
port: 5432
pool:
min: 5
max: 20
"""
# Always use safe_load (prevents arbitrary code execution)
data = yaml.safe_load(yaml_string)
json_output = json.dumps(data, indent=2, ensure_ascii=False)
print(json_output)
# ===== JSON to YAML =====
json_string = '{"name": "app", "version": "2.0", "features": ["auth", "logging"]}'
json_data = json.loads(json_string)
yaml_output = yaml.dump(json_data, default_flow_style=False, allow_unicode=True)
print(yaml_output)
# ===== File conversion =====
# YAML file to JSON file
with open('config.yaml', 'r') as yf:
config = yaml.safe_load(yf)
with open('config.json', 'w') as jf:
json.dump(config, jf, indent=2)
# JSON file to YAML file
with open('data.json', 'r') as jf:
data = json.load(jf)
with open('data.yaml', 'w') as yf:
yaml.dump(data, yf, default_flow_style=False)
# ===== Handle multi-document YAML =====
multi_yaml = """
---
name: doc1
type: config
---
name: doc2
type: data
"""
docs = list(yaml.safe_load_all(multi_yaml))
print(json.dumps(docs, indent=2))
# ===== Preserve key order (Python 3.7+) =====
# dict maintains insertion order by default
ordered = yaml.safe_load(yaml_string)
print(json.dumps(ordered, indent=2)) # keys stay in YAML orderBash / CLI (yq)
Fur die Kommandozeilen-Konvertierung ist yq am effizientesten:
# ===== yq: YAML processor (like jq for YAML) =====
# Convert YAML file to JSON
yq -o=json config.yaml
# Convert YAML to JSON and save to file
yq -o=json config.yaml > config.json
# Convert JSON to YAML
yq -P config.json
# Convert JSON to YAML and save
yq -P config.json > config.yaml
# Extract a specific field from YAML as JSON
yq -o=json '.server.port' config.yaml
# ===== Python one-liner =====
# YAML to JSON (stdin)
cat config.yaml | python3 -c \
'import sys,yaml,json; json.dump(yaml.safe_load(sys.stdin),sys.stdout,indent=2)'
# YAML to JSON (file)
python3 -c \
'import yaml,json; print(json.dumps(yaml.safe_load(open("config.yaml")),indent=2))'
# JSON to YAML
cat data.json | python3 -c \
'import sys,yaml,json; print(yaml.dump(json.load(sys.stdin),default_flow_style=False))'
# ===== Ruby one-liner =====
ruby -ryaml -rjson -e 'puts JSON.pretty_generate(YAML.load($stdin.read))' < config.yaml
# ===== Pipe YAML from curl to JSON =====
curl -s https://raw.githubusercontent.com/example/repo/main/config.yaml | \
yq -o=json
# ===== Validate YAML before converting =====
yamllint config.yaml && yq -o=json config.yamlGo (gopkg.in/yaml.v3)
In Go bietet gopkg.in/yaml.v3 robustes YAML-Parsing:
package main
import (
"encoding/json"
"fmt"
"log"
"gopkg.in/yaml.v3"
)
func main() {
// YAML input string
yamlData := []byte(`
server:
host: localhost
port: 8080
ssl: true
database:
name: myapp
replicas:
- host: db1.example.com
port: 5432
- host: db2.example.com
port: 5432
`)
// Parse YAML into interface{}
var data interface{}
err := yaml.Unmarshal(yamlData, &data)
if err != nil {
log.Fatalf("YAML parse error: %v", err)
}
// Convert map[string]interface{} keys for JSON compatibility
data = convertMapKeys(data)
// Marshal to JSON
jsonData, err := json.MarshalIndent(data, "", " ")
if err != nil {
log.Fatalf("JSON marshal error: %v", err)
}
fmt.Println(string(jsonData))
}
// convertMapKeys recursively converts map[interface{}]interface{}
// to map[string]interface{} for JSON compatibility
func convertMapKeys(v interface{}) interface{} {
switch v := v.(type) {
case map[string]interface{}:
result := make(map[string]interface{})
for key, val := range v {
result[key] = convertMapKeys(val)
}
return result
case []interface{}:
for i, val := range v {
v[i] = convertMapKeys(val)
}
return v
default:
return v
}
}JSON-zu-YAML Konvertierung
Die Umkehrrichtung ist ebenso wichtig, wenn API-JSON als YAML-Konfiguration gespeichert werden soll.
Kommentare gehen verloren bei der Hin-und-Zuruck-Konvertierung. Verwenden Sie ruamel.yaml zum Erhalt.
Best Practices: 2 Leerzeichen Einruckung, Flow-Style vermeiden, zweideutige Strings zitieren, Ausgabe validieren.
Haufige YAML-Fallstricke
YAMLs Flexibilitat bringt einige Stolperfallen mit sich:
Tabs vs. Leerzeichen — YAML verbietet Tabs fur die Einruckung.
Boolean-Falle — yes, no, on, off werden als Booleans interpretiert.
# The YAML boolean trap - these all become true or false in JSON!
# YAML 1.1 boolean values (case-insensitive):
is_active: yes # â true
is_active: no # â false
is_active: on # â true
is_active: off # â false
is_active: y # â true
is_active: n # â false
is_active: true # â true
is_active: false # â false
# Real-world problems:
countries:
- US # string "US" â
- GB # string "GB" â
- NO # boolean false â (Norway disappears!)
- FR # string "FR" â
# Fix: always quote ambiguous values
countries:
- "US"
- "GB"
- "NO" # string "NO" â
- "FR"
# Version numbers are also problematic:
version: 1.0 # â float 1 (not string "1.0")
version: "1.0" # â string "1.0" âMehrzeilige Strings — | behalt Zeilenumbruche, > ersetzt sie durch Leerzeichen.
# YAML multiline string variants
# Literal block scalar (|) - preserves newlines
description: |
This is line one.
This is line two.
This is line three.
# JSON: "This is line one.\nThis is line two.\nThis is line three.\n"
# Folded block scalar (>) - replaces newlines with spaces
description: >
This is a long
paragraph that will
be folded into one line.
# JSON: "This is a long paragraph that will be folded into one line.\n"
# Chomping indicators:
keep_trailing: |+ # Keep ALL trailing newlines
text
strip_trailing: |- # Strip ALL trailing newlines
text
clip_trailing: | # Keep exactly ONE trailing newline (default)
textSonderzeichen — Doppelpunkte und Klammern in Werten mussen zitiert werden.
Anker und Aliase — Werden bei JSON-Konvertierung vollstandig aufgelost.
# YAML anchors and aliases
# Define an anchor with &
defaults: &default_settings
adapter: postgres
host: localhost
port: 5432
# Reuse with alias *
development:
database:
<<: *default_settings # Merge key: inherits all defaults
database: myapp_dev
production:
database:
<<: *default_settings # Same defaults
database: myapp_prod
host: db.production.com # Override specific values
# After JSON conversion (anchors fully expanded):
# {
# "defaults": { "adapter": "postgres", "host": "localhost", "port": 5432 },
# "development": {
# "database": {
# "adapter": "postgres", "host": "localhost",
# "port": 5432, "database": "myapp_dev"
# }
# },
# "production": {
# "database": {
# "adapter": "postgres", "host": "db.production.com",
# "port": 5432, "database": "myapp_prod"
# }
# }
# }Zahlen und Daten — 1.0 wird zum Float, nicht zum String "1.0".
YAML Best Practices
Befolgen Sie diese Praktiken fur sauberes YAML:
Konsistente Einruckung — 2 Leerzeichen, passend zu Kubernetes-Konventionen.
Strings defensiv zitieren — Im Zweifel Anfuhrungszeichen verwenden.
Boolean-Falle vermeiden — Auf Landercodes und Umschaltwerte achten.
Schema-Validierung — Mit JSON Schema validieren.
yamllint verwenden — In die CI/CD-Pipeline integrieren.
# .yamllint.yml configuration example
---
extends: default
rules:
line-length:
max: 120
allow-non-breakable-words: true
indentation:
spaces: 2
indent-sequences: true
comments:
min-spaces-from-content: 1
truthy:
check-keys: true
allowed-values: ['true', 'false']
document-start:
present: true
trailing-spaces: enable
new-line-at-end-of-file: enable
# Run yamllint:
# yamllint .
# yamllint config.yaml
# yamllint -d "{extends: default}" config.yamlKommentare klug einsetzen — Sie gehen bei JSON-Konvertierung verloren.
Haufig gestellte Fragen
Was ist der Unterschied zwischen YAML und JSON?
YAML verwendet Einruckung, unterstutzt Kommentare und bietet erweiterte Funktionen. JSON verwendet Klammern, hat keine Kommentare und begrenztere Typen. YAML ist fur Konfiguration bevorzugt, JSON fur APIs.
Wie konvertiere ich YAML zu JSON?
Nutzen Sie Online-Tools, yq in der CLI oder Bibliotheken: js-yaml in JavaScript, PyYAML in Python, gopkg.in/yaml.v3 in Go.
Wann YAML und wann JSON verwenden?
YAML fur menschlich bearbeitete Konfigurationsdateien. JSON fur APIs und Datenaustausch zwischen Services.
Die Beherrschung der YAML-zu-JSON-Konvertierung ist fur modernes DevOps unerlasslich. Nutzen Sie unser kostenloses Tool und den YAML-Validator.
Konvertieren Sie YAML zu JSON und JSON zu YAML sofort mit unserem kostenlosen Tool.