YAML (YAML Ain't Markup Language) is a human-readable data serialization format often used for configuration files, data exchange, and configuration management tools. It is designed to be easy to read and write, making it a popular alternative to JSON and XML.
When working with YAML, proper formatting and validation are important to ensure the syntax is correct and easily readable. A well-formatted YAML file helps prevent errors and improves maintainability.
In JavaScript, you can use the js-yaml library to parse (validate) and stringify (format) YAML data. Here’s how you can use it with the methods jsyaml.load()
and jsyaml.dump()
jsyaml.dump()
The jsyaml.dump()
method converts a JavaScript object into a YAML-formatted string. You can specify indentation for pretty-printing the YAML. Example:
const jsyaml = require('js-yaml'); // or you can use CDN with pure vanilla JS const parsedYaml = { name: "John Doe", age: 30, skills: ["JavaScript", "Node.js", "YAML"] }; const formattedYaml = jsyaml.dump(parsedYaml, { indent: 2 }); console.log(formattedYaml); /* Output: name: John Doe age: 30 skills: - JavaScript - Node.js - YAML */
jsyaml.load()
The jsyaml.load()
method parses a YAML string and converts it into a JavaScript object. If the YAML string contains invalid syntax, it will throw an error, making it a useful tool for validation. Example:
const yamlText = ` name: Jane Doe age: 25 skills: - Python - Ruby `; try { const parsedData = jsyaml.load(yamlText); // Valid YAML console.log(parsedData); // Output: { name: 'Jane Doe', age: 25, skills: [ 'Python', 'Ruby' ] } } catch (error) { console.error("Invalid YAML:", error.message); }
If the YAML string is improperly formatted (e.g., missing indentation, incorrect data types), jsyaml.load()
will throw an error. For example:
const invalidYamlText = ` name: John Doe age: 30 skills: - JavaScript - Node.js`; // Invalid YAML (missing indentation) try { const parsedData = jsyaml.load(invalidYamlText); console.log(parsedData); } catch (error) { console.error("Error:", error.message); // Output: Error: invalid YAML (missing indentation) }