JSON vs YAML Conversion
JSON and YAML Feature Comparison
JSON (JavaScript Object Notation) and YAML (YAML Ain't Markup Language) are two popular data serialization formats. JSON is a subset of JavaScript with concise syntax, easy parsing, and is the standard format for Web APIs. YAML is a superset of JSON, using indentation to represent hierarchy, supporting comments, more readable, and commonly used for configuration files.
JSON's advantages include: fast parsing speed, native support in all programming languages, and suitability for data exchange. YAML's advantages include: excellent human readability, support for comments, anchors and references to reduce repetition, and support for multiple data types. When choosing a format, data exchange typically uses JSON, while configuration files typically use YAML.
Format Conversion Methods
// JavaScript JSON and YAML conversion
const yaml = require('js-yaml');
// JSON to YAML
const jsonData = {
name: 'my-app',
version: '1.0.0',
dependencies: {
express: '^4.18.0',
lodash: '^4.17.0'
},
scripts: {
start: 'node server.js',
dev: 'nodemon server.js'
}
};
const yamlString = yaml.dump(jsonData, {
indent: 2,
lineWidth: 80,
noRefs: true
});
console.log(yamlString);
// name: my-app
// version: 1.0.0
// dependencies:
// express: ^4.18.0
// lodash: ^4.17.0
// YAML to JSON
const yamlContent = `
server:
host: localhost
port: 3000
database:
host: db.example.com
port: 5432
`;
const parsed = yaml.load(yamlContent);
console.log(JSON.stringify(parsed, null, 2));
// {
// "server": { "host": "localhost", "port": 3000 },
// "database": { "host": "db.example.com", "port": 5432 }
// }
YAML Advanced Features
# YAML advanced features examples
# Anchors and references (reduce repetition)
defaults: &defaults
adapter: postgres
host: localhost
development:
database: dev_db
<<: *defaults # Inherits all properties from defaults
production:
database: prod_db
<<: *defaults
# Multi-line strings
description: |
This is a multi-line
description that preserves
line breaks.
# Tags and data types
timestamp: 2024-01-01T12:00:00
version: 1.0.0 # Auto-detected as string
count: 42 # Auto-detected as integer
ratio: 3.14 # Auto-detected as float
enabled: true # Auto-detected as boolean
Recommended Tools
JSON Formatter is an online JSON formatting and validation tool. YAML Lint is a YAML syntax validation tool. js-yaml is a JavaScript YAML parsing library. yq is a command-line YAML processing tool.