How to Parse YAML in JavaScript
Complete guide to loading and dumping YAML in JavaScript using js-yaml — the most widely used YAML library for Node.js and the browser.
Install js-yaml
npm install js-yaml
Parse a YAML String
import jsyaml from 'js-yaml';
const yamlString = `
name: Alice
age: 30
skills:
- JavaScript
- YAML
- Node.js
`;
const data = jsyaml.load(yamlString);
console.log(data);
// { name: 'Alice', age: 30, skills: ['JavaScript', 'YAML', 'Node.js'] }
Read a YAML File in Node.js
import fs from 'fs';
import jsyaml from 'js-yaml';
const config = jsyaml.load(fs.readFileSync('config.yaml', 'utf8'));
console.log(config.name);
Dump JavaScript Object to YAML
import jsyaml from 'js-yaml';
const data = { name: 'Alice', age: 30, skills: ['JavaScript', 'YAML'] };
const yaml = jsyaml.dump(data, {
indent: 2,
lineWidth: -1, // no line wrapping
noRefs: true // no YAML references/aliases
});
console.log(yaml);
Use js-yaml in the Browser
<!-- Load from CDN -->
<script src="https://cdn.jsdelivr.net/npm/js-yaml@4/dist/js-yaml.min.js"></script>
<script>
const data = jsyaml.load('name: Alice\nage: 30');
console.log(data); // { name: 'Alice', age: 30 }
</script>
Convert YAML to JSON
import jsyaml from 'js-yaml';
const yamlString = `name: Alice\nage: 30`;
const data = jsyaml.load(yamlString);
const json = JSON.stringify(data, null, 2);
console.log(json);
Need to format YAML without writing code?
Paste any YAML into the free online formatter — instant results, no setup needed.
Open YAML Formatter →Frequently Asked Questions
How do I parse YAML in JavaScript?
Install js-yaml with npm install js-yaml, then use jsyaml.load(yamlString). It returns a plain JavaScript object you can work with directly.
Is there a built-in YAML parser in Node.js?
No. Node.js does not include a built-in YAML parser. js-yaml is the standard go-to — it is lightweight (39KB), well-maintained, and used by millions of projects including Webpack and ESLint.
How do I handle YAML parse errors in JavaScript?
Wrap jsyaml.load() in a try/catch. The error object has a mark property with line and column for the error position.