How to convert YAML into JSON in JavaScript

When working with configuration data, its common to encounter scenarios where the data needs to be converted into another format. YAML is one of the most popular configurations file types used in modern web development.

If you are looking to convert YAML to JSON however there is no native JavaScript parsing functionality. Thankfully, a great package exists that easily facilities this conversion.

js-yaml acts as a standalone JavaScript YAML parser. It works in node.js and all major browsers. It will take a YAML file like this:

# An employee record 
    name: Tommy Verceti 
    job: Developer 
    skill: Elite

and parse it into familiar JSON:

{ Tommy: { name: 'Tommy Verceti', job: 'Developer', skill: 'Elite' } }

You can use the online tool to do this:

Or if you want this done in your Node environment, install the dependency locally :

npm install js-yaml

And in a Node.js file:

const inputYML = 'input.yml';
const outputJSON = 'output.json';
const yaml = require('js-yaml');
const fs = require('fs');
const obj = yaml.load(fs.readFileSync(inputYML, {encoding: 'utf-8'})); 
//this code if you want to save file locally
fs.writeFileSync(outputJSON, JSON.stringify(obj, null, 2));

This conversion is pretty easily done. I hope this helped.

Proudly published with Gatsby