DEV Community

Cover image for Config Translation: Writing a Recursive JSON to YAML Parser in Vanilla TypeScript
kandz
kandz

Posted on

Config Translation: Writing a Recursive JSON to YAML Parser in Vanilla TypeScript

If you work in DevOps, cloud engineering, or full-stack web development, you are constantly switching between configuration syntaxes.

You might have a nested REST API response in JSON that you need to map into a YAML deployment configuration for Kubernetes, Docker Compose, or GitHub Actions.

While heavy packages like js-yaml or yaml exist, importing large dependencies just to translate a simple payload is inefficient. Instead, you can write a lightweight, recursive translation parser in vanilla TypeScript that operates with zero dependencies.


The Syntactic Divide: Braces vs. Indentation

Before writing the parser, we must analyze the structural differences:

  • JSON: A strict, bracket-based format derived from JavaScript object literals. It relies on curly braces {} for maps, square brackets [] for arrays, commas as separators, and double quotes for keys.
  • YAML: An indentation-based format designed for human readability. It strips braces, brackets, and commas, using consecutive spaces (usually 2) to establish parent-child hierarchies and hyphens - to denote array lists.

Writing the Recursive JSON-to-YAML Parser

To translate a nested JSON structure into indented YAML, we must recursively traverse the object tree.

Here is a clean, dependency-free TypeScript parser that maps objects, arrays, strings, numbers, booleans, and null values:

function jsonToYaml(obj: any, indent: number = 0): string {
  const spacing = ' '.repeat(indent);

  if (obj === null) return 'null';
  if (typeof obj === 'string') return `"${obj.replace(/"/g, '\\"')}"`;
  if (typeof obj === 'number' || typeof obj === 'boolean') return String(obj);

  // Handle Arrays
  if (Array.isArray(obj)) {
    if (obj.length === 0) return '[]';
    return obj
      .map((item) => `${spacing}- ${jsonToYaml(item, indent + 2).trim()}`)
      .join('\n');
  }

  // Handle Nested Objects (Maps)
  if (typeof obj === 'object') {
    const keys = Object.keys(obj);
    if (keys.length === 0) return '{}';
    return keys
      .map((key) => {
        const value = obj[key];
        const formattedKey = /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key) ? key : `"${key}"`;

        if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
          return `${spacing}${formattedKey}:\n${jsonToYaml(value, indent + 2)}`;
        }
        return `${spacing}${formattedKey}: ${jsonToYaml(value, indent + 2).trim()}`;
      })
      .join('\n');
  }

  return '';
}

// Example usage:
const payload = {
  name: "KandZ Tools",
  active: true,
  metadata: {
    version: 2.1,
    tags: ["utility", "privacy"]
  }
};

console.log(jsonToYaml(payload));
Enter fullscreen mode Exit fullscreen mode

How the Parser Resolves Tree Structures:

  1. Base Cases: If the value is a string, number, boolean, or null, it converts it directly into its standard YAML representation.
  2. Array Traversal: If the value is an array, it iterates through each item, prefixes it with a hyphen -, and recursively indents nested children.
  3. Object Traversal: If the value is an object, it iterates through its keys, checks if keys contain standard alphanumeric characters (wrapping them in quotes if they contain special symbols), and recursively indents the values.

Safe and Private Configuration Audits

Copy-pasting internal server configuration files, Kubernetes manifests, or database schemas into public online translators represents a massive security risk, as public portals can log credentials, keys, or proprietary infrastructures in remote databases.

To address this, we built a free, 100% Client-Side JSON to YAML / YAML to JSON Converter at KandZ Tools.

Our utility executes all recursive conversions exclusively inside your browser's local memory (RAM). Your configurations, parameters, and structural trees are never transmitted to external databases, keeping your system designs private.

Translate your configuration syntaxes securely: https://tools.kandz.me/yaml-converter


Enter fullscreen mode Exit fullscreen mode

Top comments (0)