How to parse YAML file in JavaScript? [SOLVED]


JavaScript

Introduction

JavaScript is a popular programming language that is often used in web development. It can be used to build interactive and dynamic websites and is often used in combination with HTML and CSS. JavaScript also has the ability to parse and manipulate data in other formats, such as YAML (Yet Another Markup Language).

YAML is a human-readable data serialization format that is commonly used for configuration files, data storage, and data exchange. It is designed to be easy to read and write and is often used as an alternative to JSON and XML. YAML data is organized into a series of key-value pairs, similar to a dictionary in Python or an object in JavaScript.

In this article, we will discuss multiple ways to parse YAML in JavaScript using NodeJS libraries.

 

Parse YAML with NodeJS libraries

There are several ways to parse YAML data in JavaScript. One option is to use a third-party library, such as js-yaml or yaml-js. These libraries provide functions for parsing YAML data and converting it into a JavaScript object or array.

 

1. Using js-yaml library to parse YAML

The js-yaml library provides a easy YAML parser for the data serialization langauge. We can use the methods present within the library to parse YAML to access each data point.

To use the library, we have to install using the npm command below

npm install js-yaml

For example, using the js-yaml library, we could parse a YAML string like this:

const yaml = require("js-yaml");

let yamlString = `
name: John 
age: 30
city: New York
`;
let obj = yaml.load(yamlString);
console.log(obj.name);

Output

John

If we have a YAML file (.yaml or .yml file), we can make use of the fs library to load the file and then load the YAML object structure.

To illustrate the way we can parse YAML files, we can save the below structure as test.yml

name: Janet Jackson
age: 30
email: jjackson@gmail.com
address:
  street: 44 Broadway Street
  city: New York
  state: New York
  zip: 10001
status:
  account: true
  subscription: premium
occupation: actress

Afterward, we can make use of the fs library method - readFileSync - to load the test.yml file and use the load method to parse the YAML structure and access via the typical object dot notation.

const yaml = require("js-yaml");
const fs = require("fs");

let yamlFile = fs.readFileSync("test.yml", "utf8");
let loadedYaml = yaml.load(yamlFile);

console.log(loadedYaml);
console.log(loadedYaml.address);
console.log(loadedYaml.address.street);

Output

{
  name: 'Janet Jackson',
  age: 30,
  email: 'jjackson@gmail.com',
  address: {
    street: '44 Broadway Street',
    city: 'New York',
    state: 'New York',
    zip: 10001
  },
  status: { account: true, subscription: 'premium' },
  occupation: 'actress'
}
{
  street: '44 Broadway Street',
  city: 'New York',
  state: 'New York',
  zip: 10001
}
44 Broadway Street

 

2. Use the yaml library to parse YAML

Another option is to use the yaml library, which is a native JavaScript library for parsing YAML data. To use this library, we first need to install it using npm (Node Package Manager):

npm install yaml

Then, we can use the yaml.parse() function to parse a YAML string:

const yaml = require("yaml");

let yamlString = `
name: Janet 
age: 24
city: Manhattan
`;
let obj = yaml.parse(yamlString);
let name = obj.name;

console.log(name);

Output

John

Just as with the last library, we can parse YAML directly from the file itself. To illustrate this, we will make us of the test.yml file

const yaml = require("yaml");
const fs = require("fs");

let yamlFile = fs.readFileSync("test.yml", "utf-8");
let loadedYAML = yaml.parse(yamlFile);

console.log(loadedYAML.email);

Output

jjackson@gmail.com

 

3. Convert parse YAML to JSON objects

Instead of parsing YAML to string, we can try to parse YAML to a JSON object. Since both are data-exchange format, we can easily structure the YAML format to an JSON object format using the js-yaml library. In case, we need to work with JSON objects within our JavaScript environment, we can make use of built-in method - JSON.stringify() - alongside the js-yaml library to convert YAML to JSON.

Let’s illustrate this by converting the test.yml to a JSON object.

const yaml = require("js-yaml");
const fs = require("fs");

let yamlFile = fs.readFileSync("test.yml", "utf8");
let loadedYaml = yaml.load(yamlFile);

let yamlAsJSON = JSON.stringify(loadedYaml, null, 2);
console.log(yamlAsJSON);

Output

{
  "name": "Janet Jackson",
  "age": 30,
  "email": "jjackson@gmail.com",
  "address": {
    "street": "44 Broadway Street",
    "city": "New York",
    "state": "New York",
    "zip": 10001
  },
  "status": {
    "account": true,
    "subscription": "premium"
  },
  "occupation

We can store the output as a JSON file - output.json.

const yaml = require("js-yaml");
const fs = require("fs");

const outputJSON = "output.json";

let yamlFile = fs.readFileSync("test.yml", "utf8");
let loadedYaml = yaml.load(yamlFile);

fs.writeFileSync(outputJSON, JSON.stringify(loadedYaml, null, 2));

The output of the code would be a newly created filed called output.json with the JSON object structure.

 

Summary

Developers can use YAML parsing in JavaScript to work with configuration files or data from various sources. For example, a developer may use a YAML configuration file to store application settings, and then parse the YAML data in order to use the settings in the application. YAML parsing is also often used in combination with other technologies, such as Node.js or Docker.

In conclusion, YAML parsing is a useful feature of JavaScript that allows developers to work with data in a convenient and human-readable format. By using a library like js-yaml or yaml, developers can easily parse YAML data and convert it into a JavaScript object or array for use in their applications. YAML parsing is commonly used for configuration files and data storage, and is an important skill for any developer working with this popular data serialization format.

 

References

yaml - npm (npmjs.com)
js-yaml - npm (npmjs.com)
YAML - Wikipedia

 

Views: 455
Olorunfemi Akinlua

Olorunfemi Akinlua

He is boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs user-friendly interfaces to enhance digital experiences across various domains. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment