Task 856: .YML File Format

Task 856: .YML File Format

The .YML file format refers to files using the YAML (YAML Ain't Markup Language) specification, a human-readable data serialization standard commonly employed for configuration and data exchange. The extension .YML is interchangeable with .YAML, as both denote the same format.

1. List of Properties Intrinsic to the .YML File Format

Based on the official YAML specification (version 1.2), the following are the core properties and structural elements intrinsic to the format. These define its syntax, semantics, and behavior within file systems as a text-based, platform-independent serialization method:

  • Encoding: Supports UTF-8 (default), UTF-16, or UTF-32 character encodings for text representation.
  • Document Structure: Allows multiple documents within a single file, delimited by '---' (start) and '...' (end, optional).
  • Indentation Sensitivity: Uses whitespace (spaces or tabs) for hierarchical nesting, with consistent indentation required for structure.
  • Comments: Lines or inline text prefixed with '#' are ignored as comments.
  • Scalars: Basic data types including strings (quoted with single/double quotes or unquoted), integers, floating-point numbers, booleans (true/false), and null (~ or null).
  • Sequences: Ordered lists denoted by '-' followed by items, supporting nested structures.
  • Mappings: Key-value pairs in the form 'key: value', with keys typically being strings and values any valid YAML type, allowing nesting.
  • Flow Style: Compact representations using '[]' for sequences and '{}' for mappings, as an alternative to block style.
  • Anchors and Aliases: Reuse of nodes via anchors ('&label') and references ('*label') to avoid duplication.
  • Tags: Explicit type declarations prefixed with '!' (e.g., !!int for integer), including custom tags.
  • Directives: Metadata lines starting with '%', such as %YAML for version specification or %TAG for tag shorthand definitions.
  • Portability: Text-based and file-system agnostic, with no binary headers or magic numbers; files are typically small and editable in any text editor.

These properties ensure YAML's compatibility across systems while prioritizing readability and minimalism.

Note that .YML and .YAML extensions are equivalent for YAML files. The following are direct download links to sample files:

3. Ghost Blog Embedded HTML JavaScript for Drag-and-Drop .YML File Dump

The following is an HTML snippet with embedded JavaScript suitable for embedding in a Ghost blog post (via the HTML card in the editor). It enables users to drag and drop a .YML file, parses it using the js-yaml library (loaded from a CDN), and displays the properties (i.e., the parsed data structure) on the screen. The output is a formatted JSON representation of the YAML content, reflecting the format's properties as applied in the file.

Drag and drop a .YML file here

4. Python Class for Handling .YML Files

The following Python class uses the pyyaml library (import as yaml) to open, decode (parse), read, write, and print the properties (parsed data) of a .YML file to the console.

import yaml

class YmlHandler:
    def __init__(self, filename):
        self.filename = filename
        self.data = None

    def read_and_decode(self):
        """Opens and decodes (parses) the .YML file."""
        with open(self.filename, 'r', encoding='utf-8') as file:
            self.data = yaml.safe_load(file)

    def print_properties(self):
        """Prints all properties (parsed data) to the console."""
        if self.data is None:
            print("No data loaded. Call read_and_decode() first.")
            return
        print(yaml.dump(self.data, default_flow_style=False))

    def write(self, new_data):
        """Writes new data to the .YML file."""
        with open(self.filename, 'w', encoding='utf-8') as file:
            yaml.dump(new_data, file, default_flow_style=False)

# Example usage:
# handler = YmlHandler('example.yml')
# handler.read_and_decode()
# handler.print_properties()
# handler.write({'new_key': 'new_value'})

5. Java Class for Handling .YML Files

The following Java class uses the SnakeYAML library (org.yaml.snakeyaml.Yaml) to open, decode (parse), read, write, and print the properties (parsed data) of a .YML file to the console. Assume SnakeYAML is included in the classpath.

import org.yaml.snakeyaml.Yaml;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.IOException;
import java.util.Map;

public class YmlHandler {
    private String filename;
    private Object data;

    public YmlHandler(String filename) {
        this.filename = filename;
        this.data = null;
    }

    public void readAndDecode() throws IOException {
        // Opens and decodes (parses) the .YML file.
        Yaml yaml = new Yaml();
        try (InputStream inputStream = new FileInputStream(filename)) {
            this.data = yaml.load(inputStream);
        }
    }

    public void printProperties() {
        // Prints all properties (parsed data) to the console.
        if (data == null) {
            System.out.println("No data loaded. Call readAndDecode() first.");
            return;
        }
        Yaml yaml = new Yaml();
        System.out.println(yaml.dump(data));
    }

    public void write(Object newData) throws IOException {
        // Writes new data to the .YML file.
        Yaml yaml = new Yaml();
        try (FileWriter writer = new FileWriter(filename)) {
            yaml.dump(newData, writer);
        }
    }

    // Example usage:
    // public static void main(String[] args) throws IOException {
    //     YmlHandler handler = new YmlHandler("example.yml");
    //     handler.readAndDecode();
    //     handler.printProperties();
    //     handler.write(Map.of("new_key", "new_value"));
    // }
}

6. JavaScript Class for Handling .YML Files

The following JavaScript class uses the js-yaml library to open (via FileReader in a browser context), decode (parse), read, write (via Blob download), and print the properties (parsed data) of a .YML file to the console. Assume js-yaml is loaded (e.g., via script tag or module import).

class YmlHandler {
    constructor(filename) {
        this.filename = filename;
        this.data = null;
    }

    readAndDecode(callback) {
        // Opens and decodes (parses) the .YML file (async for browser FileReader).
        const reader = new FileReader();
        reader.onload = (event) => {
            try {
                this.data = jsyaml.load(event.target.result);
                callback(null);
            } catch (error) {
                callback(error);
            }
        };
        // Assume file object is provided; in practice, use input element.
        // For node.js, use fs.readFileSync instead.
        // Example: document.getElementById('fileInput').files[0]
        reader.readAsText(file); // 'file' should be replaced with actual File object.
    }

    printProperties() {
        // Prints all properties (parsed data) to the console.
        if (this.data === null) {
            console.log('No data loaded. Call readAndDecode() first.');
            return;
        }
        console.log(jsyaml.dump(this.data));
    }

    write(newData) {
        // Writes new data to a .YML file (downloads in browser via Blob).
        const yamlText = jsyaml.dump(newData);
        const blob = new Blob([yamlText], { type: 'text/yaml' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = this.filename;
        a.click();
        URL.revokeObjectURL(url);
    }
}

// Example usage (browser):
// const handler = new YmlHandler('example.yml');
// handler.readAndDecode((err) => {
//     if (!err) handler.printProperties();
// });
// handler.write({ new_key: 'new_value' });

7. C++ Class for Handling .YML Files

The following C++ class uses the yaml-cpp library to open, decode (parse), read, write, and print the properties (parsed data) of a .YML file to the console. Assume yaml-cpp is linked during compilation.

#include <iostream>
#include <fstream>
#include <yaml-cpp/yaml.h>

class YmlHandler {
private:
    std::string filename;
    YAML::Node data;

public:
    YmlHandler(const std::string& filename) : filename(filename) {}

    void readAndDecode() {
        // Opens and decodes (parses) the .YML file.
        std::ifstream file(filename);
        if (file) {
            data = YAML::Load(file);
        } else {
            std::cerr << "Failed to open file: " << filename << std::endl;
        }
    }

    void printProperties() {
        // Prints all properties (parsed data) to the console.
        if (data.IsNull()) {
            std::cout << "No data loaded. Call readAndDecode() first." << std::endl;
            return;
        }
        std::cout << data << std::endl;
    }

    void write(const YAML::Node& newData) {
        // Writes new data to the .YML file.
        std::ofstream file(filename);
        if (file) {
            file << newData;
        } else {
            std::cerr << "Failed to write to file: " << filename << std::endl;
        }
    }
};

// Example usage:
// int main() {
//     YmlHandler handler("example.yml");
//     handler.readAndDecode();
//     handler.printProperties();
//     YAML::Node newData;
//     newData["new_key"] = "new_value";
//     handler.write(newData);
//     return 0;
// }