YAML Formatter & Validator

Enter YAML

Output

Enter YAML to validate or format

About YAML Formatting and Validation

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.

Why Use YAML Formatter and Validator?

  • Improve Readability: Make YAML data easier to read and understand by applying consistent indentation.
  • Quickly Find Errors: Validate and check for syntax issues in YAML files to avoid errors in configuration.
  • Standard Compliance: Ensure your YAML files adhere to the correct syntax and structure before using them in your application or infrastructure.
  • Save Time: Simplify your workflow by formatting and validating YAML instantly.

Using YAML in JavaScript

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()

Formatting YAML with 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
*/
Validating YAML with 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);
}
Catching Invalid YAML

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)
}