Converting JSON to YAML in JavaScript

Simple script to convert Json To Yaml

Ravi Tiwari
2 min readMar 1, 2023
Json To Yaml

JSON and YAML are two commonly used data serialization formats. JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. YAML (YAML Ain’t Markup Language) is a human-readable data serialization format that is often used for configuration files and data exchange between languages.

In this article, we will be discussing a JavaScript code that converts JSON data to YAML data using the js-yaml package.

The first thing we do in the code is require the fs and js-yaml packages. The fs package is a built-in Node.js module that provides an API for working with the file system. The js-yaml package is a third-party package that allows us to work with YAML data.

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

Next, we get the input file path and output file path from the command line arguments using the process.argv array.

const inputFilePath = process.argv[2];
const outputFilePath = process.argv[3];

We then use the fs.readFileSync() method to read the input file and store its contents in a variable called jsonData. The "utf8" argument specifies the file encoding.

const jsonData = fs.readFileSync(inputFilePath, "utf8");

We then use the JSON.parse() method to parse the jsonData into a JavaScript object called parsedData.

const parsedData = JSON.parse(jsonData);

We then use the jsYaml.dump() method to convert the parsedData object to YAML data and store it in a variable called yamlData.

const yamlData = jsYaml.dump(parsedData);

Finally, we use the fs.writeFileSync() method to write the yamlData to the output file. The "utf8" argument specifies the file encoding.

fs.writeFileSync(outputFilePath, yamlData, "utf8");

If any errors occur during the reading or writing of the files, we catch them using a try...catch block and log the error message to the console.

try {
// read and write files here
} catch (error) {
console.error(`Error reading/writing file: ${error.message}`);
process.exit(1);
}

In conclusion, this JavaScript code is a simple and effective way to convert JSON data to YAML data using the js-yaml package. It demonstrates how to use the fs and js-yaml packages, and how to read and write files using the Node.js file system API.

Source Code : https://github.com/rtiwariops/CodeHub/tree/main/utility/json2yaml-node

--

--

Ravi Tiwari
Ravi Tiwari

Written by Ravi Tiwari

Experienced hands-on CTO with 20+ years of cloud native microservices expertise, driving solutions for large-scale enterprises.

Responses (1)