Convert JSON to YAML in JavaScript/Node.js [Complete Guide]
Convert JSON to YAML in JavaScript using the js-yaml library. Install with
npm install js-yaml, then use yaml.dump() to convert JSON objects
to YAML strings. Not sure which format suits your
project? See our YAML vs JSON comparison. This guide
covers JS JSON to YAML conversion in both Node.js and browser
environments with the same simple API.
Install js-yaml
JavaScript doesn't have built-in YAML support
(though it has native JSON with JSON.parse()). Install the js-yaml
library,
the most popular npm package for JSON to YAML conversion. Prefer a different language? Check our
Python, Java, or Go guides.
# Install js-yaml using npm
npm install js-yaml
# Or using yarn
yarn add js-yaml
# Verify installation
npm list js-yaml
js-yaml supports YAML 1.2 specification and is used by thousands of projects including ESLint, Webpack, and many others.
Convert JSON to YAML (Node.js)
Here's how to convert JSON to YAML in Node.js:
Basic Conversion
const yaml = require('js-yaml');
// Your JSON data (or any JavaScript object)
const jsonData = {
name: "my-app",
version: "1.0.0",
dependencies: {
express: "^4.18.0",
lodash: "^4.17.0"
},
scripts: {
start: "node server.js",
test: "jest"
}
};
// Convert to YAML
const yamlString = yaml.dump(jsonData);
console.log(yamlString);
Output:
name: my-app
version: 1.0.0
dependencies:
express: ^4.18.0
lodash: ^4.17.0
scripts:
start: node server.js
test: jest
ES Modules (import syntax)
import yaml from 'js-yaml';
const jsonData = { name: "example", version: "1.0.0" };
const yamlString = yaml.dump(jsonData);
console.log(yamlString);
Convert YAML to JSON (Node.js)
Converting YAML back to JSON is equally simple:
const yaml = require('js-yaml');
const yamlString = `
name: my-app
version: 1.0.0
database:
host: localhost
port: 5432
`;
// Parse YAML to JavaScript object
const jsonData = yaml.load(yamlString);
// Convert to JSON string
const jsonString = JSON.stringify(jsonData, null, 2);
console.log(jsonString);
yaml.load() is safe by default
and uses SAFE_SCHEMA. For older versions (v3.x), use yaml.safeLoad() to prevent
code execution vulnerabilities. For quick one-off conversions, try our online JSON to YAML converter.
Browser Usage
js-yaml works in browsers too. Include it via CDN:
Using CDN
<!-- Include js-yaml from CDN -->
<script src="https://unpkg.com/js-yaml@4/dist/js-yaml.min.js"></script>
<script>
// js-yaml is available as window.jsyaml
const jsonData = {
name: "browser-app",
version: "1.0.0"
};
// Convert JSON to YAML
const yamlString = jsyaml.dump(jsonData);
console.log(yamlString);
// Convert YAML to JSON
const parsed = jsyaml.load(yamlString);
console.log(parsed);
</script>
With Bundlers (Webpack, Rollup, Vite)
// Works the same as Node.js when bundled
import yaml from 'js-yaml';
function convertJsonToYaml(jsonData) {
return yaml.dump(jsonData);
}
function convertYamlToJson(yamlString) {
return yaml.load(yamlString);
}
Reading and Writing Files
Read JSON File, Write YAML
const fs = require('fs');
const yaml = require('js-yaml');
function jsonFileToYaml(inputPath, outputPath) {
// Read JSON file
const jsonContent = fs.readFileSync(inputPath, 'utf8');
const data = JSON.parse(jsonContent);
// Convert and write YAML
const yamlContent = yaml.dump(data);
fs.writeFileSync(outputPath, yamlContent, 'utf8');
console.log(`Converted ${inputPath} to ${outputPath}`);
}
// Usage
jsonFileToYaml('config.json', 'config.yaml');
Read YAML File, Write JSON
const fs = require('fs');
const yaml = require('js-yaml');
function yamlFileToJson(inputPath, outputPath) {
// Read YAML file
const yamlContent = fs.readFileSync(inputPath, 'utf8');
const data = yaml.load(yamlContent);
// Convert and write JSON
const jsonContent = JSON.stringify(data, null, 2);
fs.writeFileSync(outputPath, jsonContent, 'utf8');
console.log(`Converted ${inputPath} to ${outputPath}`);
}
// Usage
yamlFileToJson('config.yaml', 'config.json');
Async/Await Version
const fs = require('fs').promises;
const yaml = require('js-yaml');
async function convertJsonToYaml(inputPath, outputPath) {
const jsonContent = await fs.readFile(inputPath, 'utf8');
const data = JSON.parse(jsonContent);
const yamlContent = yaml.dump(data);
await fs.writeFile(outputPath, yamlContent, 'utf8');
}
// Usage
convertJsonToYaml('data.json', 'data.yaml')
.then(() => console.log('Done!'))
.catch(err => console.error(err));
Advanced Options
js-yaml's dump() function accepts options for customizing output:
const yaml = require('js-yaml');
const data = {
name: "example",
items: [1, 2, 3],
nested: { a: 1, b: 2 }
};
// Custom formatting options
const yamlString = yaml.dump(data, {
indent: 4, // Indentation spaces (default: 2)
lineWidth: 80, // Max line width (default: 80)
noRefs: true, // Don't use anchors/aliases
sortKeys: true, // Sort object keys alphabetically
quotingType: '"', // Quote style (single or double)
forceQuotes: false // Force quotes around all strings
});
console.log(yamlString);
| Option | Default | Description |
|---|---|---|
indent |
2 | Number of spaces for indentation |
lineWidth |
80 | Maximum line width before wrapping |
sortKeys |
false | Sort object keys alphabetically |
noRefs |
false | Disable anchors and aliases |
flowLevel |
-1 | Nesting level for flow style (-1 = block) |
Common Errors and Solutions
| Error | Cause | Solution |
|---|---|---|
Cannot find module 'js-yaml' |
Package not installed | npm install js-yaml |
YAMLException: bad indentation |
Mixed tabs/spaces in YAML | Use consistent spacing (2 spaces) |
SyntaxError: Unexpected token |
Invalid JSON input | Validate JSON before parsing |
jsyaml is not defined |
CDN script not loaded | Check CDN URL, load order |
Error Handling Example
const yaml = require('js-yaml');
const fs = require('fs');
function safeConvert(inputPath, outputPath) {
try {
const content = fs.readFileSync(inputPath, 'utf8');
const data = JSON.parse(content);
const yamlContent = yaml.dump(data);
fs.writeFileSync(outputPath, yamlContent, 'utf8');
return { success: true };
} catch (error) {
if (error instanceof SyntaxError) {
return { success: false, error: 'Invalid JSON syntax' };
}
if (error.code === 'ENOENT') {
return { success: false, error: 'File not found' };
}
return { success: false, error: error.message };
}
}
Frequently Asked Questions
How do I convert JSON to YAML in JavaScript?
Install the js-yaml library (npm install js-yaml), import it with
require('js-yaml'), then use yaml.dump(jsonObject) to
convert a JavaScript object to a YAML string. The same library works in both
Node.js and browsers.
Is there a built-in YAML parser in JavaScript?
No, JavaScript does not have built-in YAML support. You need to use a third-party
library like js-yaml (npm install js-yaml). JSON is built into JavaScript
with JSON.parse() and JSON.stringify(), but YAML requires
external packages.
Can I use js-yaml in the browser?
Yes, js-yaml works in browsers. You can include it via CDN
(unpkg.com/js-yaml) or bundle it with webpack/rollup. The API is
identical to Node.js—use jsyaml.dump() and jsyaml.load().
What is the difference between yaml.load() and yaml.safeLoad()?
In js-yaml v4+, safeLoad() was removed and load() is safe
by default. It uses SAFE_SCHEMA which doesn't allow custom JavaScript types. For
older versions, always use safeLoad() to prevent code execution.
Need to convert JSON to YAML quickly?
Use our free online converter—no installation required.
Open Converter Tool →