JSON to YAML Conversion Guide
JSON and YAML: Syntax Comparison
YAML (YAML Ain't Markup Language) and JSON are both data serialization formats. YAML is actually a superset of JSON โ all valid JSON is valid YAML. But their common syntax styles differ greatly: YAML uses indentation to express hierarchy, requires no curly braces or quotes, supports comments, and is more oriented toward human readability; JSON uses curly braces and quotes, has strict structure, no comments, and is better suited for machine parsing and transmission.
Both formats expressing the same data:
// JSON
{
"name": "Alice",
"age": 30,
"roles": ["admin", "editor"],
"address": {
"city": "Beijing",
"country": "China"
}
}
# YAML
name: Alice
age: 30
roles:
- admin
- editor
address:
city: Beijing
country: China
Rules for Converting JSON to YAML
Understanding conversion rules helps with manual adjustment and validation of conversion results: JSON objects ({}) become YAML key-value pairs with indentation for nesting; JSON arrays ([]) become YAML list items with - prefix; strings don't necessarily need quotes (except numeric strings and strings with special characters); numbers, booleans, and null are written directly without quotes; comments in YAML use #, which JSON doesn't support.
Important conversion pitfalls: in YAML, yes/no/true/false/on/off are all boolean values โ if your JSON string keys happen to be these words, they need quotes when converted to YAML. Pure numeric JSON strings (like "123") must retain quotes in YAML, otherwise they'll be parsed as integers.
Command-Line Conversion
yq is a command-line tool designed for YAML (similar to jq for JSON), supporting conversion between JSON and YAML:
# ๅฎ่ฃ
yq / Install yq
brew install yq # macOS
# ๆ / or: snap install yq
# JSON ่ฝฌ YAML / JSON to YAML
yq -p json -o yaml input.json > output.yaml
# YAML ่ฝฌ JSON / YAML to JSON
yq -p yaml -o json input.yaml > output.json
# ไปๆ ๅ่พๅ
ฅ่ฝฌๆข / Convert from stdin
cat data.json | yq -p json -o yaml
# ไฝฟ็จ python ๅ
็ฝฎๆจกๅ่ฝฌๆข
# Convert using Python built-in modules
python3 -c "import sys,json,yaml; yaml.dump(json.load(sys.stdin), sys.stdout, allow_unicode=True)" < input.json
# ไฝฟ็จ nodejs ่ฝฌๆข
# Convert using Node.js
node -e "const y=require('js-yaml'); const j=require('fs').readFileSync(0,'utf8'); process.stdout.write(y.dump(JSON.parse(j)));"
Code Implementation in Each Language
# Python
import json
import yaml
# JSON ๅญ็ฌฆไธฒ่ฝฌ YAML / JSON string to YAML
def json_to_yaml(json_str):
data = json.loads(json_str)
return yaml.dump(data, allow_unicode=True, default_flow_style=False)
# YAML ๅญ็ฌฆไธฒ่ฝฌ JSON / YAML string to JSON
def yaml_to_json(yaml_str):
data = yaml.safe_load(yaml_str)
return json.dumps(data, ensure_ascii=False, indent=2)
// JavaScript (ไฝฟ็จ js-yaml ๅบ)
// JavaScript (using js-yaml library)
import yaml from 'js-yaml';
// JSON ๅฏน่ฑก่ฝฌ YAML ๅญ็ฌฆไธฒ
function jsonToYaml(obj) {
return yaml.dump(obj, { indent: 2 });
}
// YAML ๅญ็ฌฆไธฒ่ฝฌ JSON ๅฏน่ฑก
function yamlToJson(yamlStr) {
return yaml.load(yamlStr);
}
// Go (ไฝฟ็จ gopkg.in/yaml.v3)
// Go (using gopkg.in/yaml.v3)
import (
"encoding/json"
"gopkg.in/yaml.v3"
)
func jsonToYaml(jsonBytes []byte) ([]byte, error) {
var obj interface{}
if err := json.Unmarshal(jsonBytes, &obj); err != nil {
return nil, err
}
return yaml.Marshal(obj)
}
YAML in DevOps Tool Applications
YAML is ubiquitous in the DevOps ecosystem. Understanding the JSON-YAML conversion relationship helps flexibly migrate configurations between these tools: Kubernetes: All resource configurations (Deployment, Service, ConfigMap) use YAML format, but the Kubernetes API actually accepts JSON โ kubectl converts automatically. GitHub Actions: Workflow files are YAML format; understanding their data structure helps debug complex workflow configurations. Ansible: Playbooks and inventory files use YAML; variables can be passed as JSON-format strings. Docker Compose: docker-compose.yml is YAML format.
# Kubernetes Deployment๏ผYAML๏ผ็ญๆไบ JSON ๆ ผๅผ็ API ่ฐ็จ๏ผ
# Kubernetes Deployment (YAML, equivalent to JSON-format API call)
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
labels:
app: my-app
spec:
replicas: 3
selector:
matchLabels:
app: my-app
template:
spec:
containers:
- name: app
image: my-app:latest
ports:
- containerPort: 8080
YAML-Specific Features: Anchors and References
YAML has some unique features beyond JSON, with anchors and aliases being the most practical: use &anchor_name to define an anchor and *anchor_name to reference it elsewhere, avoiding repetitive definitions. This is particularly useful in configuration files โ for example, multiple services sharing the same base configuration:
YAML also supports multi-line strings (using | to preserve newlines, > to fold newlines), document separators (---) allowing multiple YAML documents in one file (JSON doesn't support these features). These features can be manually added after converting from JSON to YAML to fully utilize YAML's expressive power.
# YAML ้็นๅๅผ็จ็คบไพ / YAML anchor and alias example
defaults: &defaults
timeout: 30
retries: 3
logLevel: info
development:
<<: *defaults # ็ปงๆฟ defaults ็ๆๆๅญๆฎต / Inherit all defaults fields
debug: true
logLevel: debug # ่ฆ็็ปงๆฟ็ๅญๆฎต / Override inherited field
production:
<<: *defaults
replicas: 10
ssl: true
Common Pitfalls During Conversion
Boolean pitfall: YAML 1.1 parses yes/no/on/off/true/false all as booleans, but YAML 1.2 (stricter) only treats true/false as boolean. Ensure the YAML library version used matches the supported spec, and add quotes around strings that might be misinterpreted.
Octal number pitfall: In YAML 1.1, numbers starting with 0 are parsed as octal (e.g., 010 parses as 8). If JSON has similarly formatted string IDs (like "0123456789"), ensure they remain quoted after conversion.
Empty string pitfall: JSON's "" needs to be written as "" or '' in YAML โ quotes can't be omitted (since unquoted empty values in YAML are parsed as null).
Indentation sensitivity: YAML is extremely sensitive to indentation; mixing tabs and spaces causes parse errors. Always use spaces (2 spaces recommended) for indentation.
Try the free tool now
Use Free Tool โ