Why Convert YAML to JSON?
Common reasons to convert YAML to JSON:
- API Integration - REST APIs typically use JSON
- JavaScript/Node.js - Native JSON support, no YAML parsing needed
- Data Processing - JSON tools and libraries are more common
- kubectl Output - Get K8s resources as JSON for scripting
- Validation - Some validators only accept JSON
Conversion Considerations:
- YAML comments are not preserved (JSON doesn't support comments)
- YAML-specific features (anchors, aliases) are resolved
- Multi-document YAML files need special handling
Convert YAML to JSON in JavaScript
Use the js-yaml library to parse YAML:
// npm install js-yaml
const yaml = require('js-yaml');
const yamlString = `
apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
data:
DATABASE_URL: postgres://localhost:5432/mydb
CACHE_TTL: "3600"
DEBUG: "false"
`;
// Parse YAML to JavaScript object
const data = yaml.load(yamlString);
// Convert to JSON string
const jsonString = JSON.stringify(data, null, 2);
console.log(jsonString);
/*
{
"apiVersion": "v1",
"kind": "ConfigMap",
"metadata": {
"name": "app-config"
},
"data": {
"DATABASE_URL": "postgres://localhost:5432/mydb",
"CACHE_TTL": "3600",
"DEBUG": "false"
}
}
*/
// Convert YAML file to JSON
const fs = require('fs');
function yamlFileToJson(yamlPath) {
const content = fs.readFileSync(yamlPath, 'utf8');
return JSON.stringify(yaml.load(content), null, 2);
}
// Handle multi-document YAML
function yamlToJsonMulti(yamlString) {
const docs = yaml.loadAll(yamlString);
return docs.map(doc => JSON.stringify(doc, null, 2));
}Convert YAML to JSON in Python
Python's PyYAML library parses YAML into Python objects:
# pip install pyyaml
import yaml
import json
yaml_string = """
server:
host: localhost
port: 8080
ssl: true
database:
connection_string: postgres://localhost/db
pool_size: 10
"""
# Parse YAML to Python dict
data = yaml.safe_load(yaml_string)
# Convert to JSON string
json_string = json.dumps(data, indent=2)
print(json_string)
# Convert YAML file to JSON file
def yaml_to_json_file(yaml_path, json_path):
with open(yaml_path, 'r') as f:
data = yaml.safe_load(f)
with open(json_path, 'w') as f:
json.dump(data, f, indent=2)
# Handle multi-document YAML (---)
def yaml_to_json_multi(yaml_string):
docs = list(yaml.safe_load_all(yaml_string))
return [json.dumps(doc, indent=2) for doc in docs]
# Safe loading prevents arbitrary code execution
# Always use safe_load() instead of load()Command Line Conversion
Convert YAML to JSON using CLI tools:
# Using yq (install: brew install yq)
yq -o=json input.yaml > output.json
# Using Python one-liner
python -c "import yaml,json,sys; print(json.dumps(yaml.safe_load(sys.stdin), indent=2))" < input.yaml > output.json
# Using Ruby (built-in)
ruby -ryaml -rjson -e 'puts JSON.pretty_generate(YAML.load(ARGF))' < input.yaml > output.json
# kubectl: Get Kubernetes resources as JSON
kubectl get deployment my-app -o json > deployment.json
kubectl get pods -o json | jq '.items[].metadata.name'
# Convert all YAML files in directory
for f in *.yaml; do
yq -o=json "$f" > "${f%.yaml}.json"
done
# Using jq with yq
yq -o=json input.yaml | jq '.metadata'Kubernetes YAML to JSON
Working with Kubernetes resources in JSON format:
# Get deployment as JSON
kubectl get deployment nginx -o json
# Get specific field using JSONPath
kubectl get pods -o jsonpath='{.items[*].metadata.name}'
# Apply JSON manifest (both formats work)
kubectl apply -f deployment.json
# Convert local YAML to JSON for API calls
cat deployment.yaml | yq -o=json | curl -X POST \
-H "Content-Type: application/json" \
-d @- \
https://kubernetes.default.svc/apis/apps/v1/deployments
# Export all resources as JSON
kubectl get all -o json > cluster-resources.jsonHandle YAML Edge Cases
YAML has features that need special handling:
const yaml = require('js-yaml');
// Multi-document YAML (separated by ---)
const multiDoc = `
---
name: doc1
---
name: doc2
`;
const docs = yaml.loadAll(multiDoc);
// Returns array of documents
// YAML anchors and aliases
const withAnchors = `
defaults: &defaults
timeout: 30
retries: 3
production:
<<: *defaults
timeout: 60
`;
const resolved = yaml.load(withAnchors);
// Anchors are resolved in JSON output:
// { defaults: { timeout: 30, retries: 3 },
// production: { timeout: 60, retries: 3 } }
// YAML special values
const specialValues = `
null_value: ~
bool_yes: yes
bool_no: no
date: 2024-01-15
`;
const parsed = yaml.load(specialValues);
// { null_value: null, bool_yes: true,
// bool_no: false, date: 2024-01-15T00:00:00.000Z }Frequently Asked Questions
Are YAML comments preserved when converting to JSON?
No, JSON doesn't support comments, so all YAML comments are lost during conversion. Document important comments elsewhere.
How do I handle multi-document YAML files?
Use yaml.loadAll() in JavaScript or yaml.safe_load_all() in Python to parse each document separately, then convert each to JSON.
What happens to YAML anchors and aliases?
They are resolved/expanded in the JSON output. The referenced content is duplicated where aliases appear.
Is the conversion lossless?
The data is preserved, but YAML-specific features (comments, anchors, document markers) are not. You can convert back to YAML but won't have the original formatting.