Try it yourself with our free Json Yaml Converter tool — runs entirely in your browser, no signup needed.

How to Convert YAML to JSON in TypeScript

How to Convert YAML to JSON in TypeScript

Converting YAML to JSON is a common task in software development, particularly when working with configuration files or data exchange formats. YAML (YAML Ain't Markup Language) is a human-readable serialization format, while JSON (JavaScript Object Notation) is a lightweight data interchange format. In this article, we will explore how to convert YAML to JSON in TypeScript, a superset of JavaScript that adds optional static typing and other features.

Quick Example

Here is a minimal example that converts a YAML string to a JSON object using the js-yaml and json libraries:

import * as yaml from 'js-yaml';
import * as json from 'json';

const yamlString = `
name: John Doe
age: 30
 occupation: Developer
`;

const jsonData = yaml.load(yamlString);
const jsonString = JSON.stringify(jsonData, null, 2);

console.log(jsonString);

This code assumes you have installed the js-yaml and json libraries using npm:

npm install js-yaml json

Step-by-Step Breakdown

Let's walk through the code line by line:

  1. import * as yaml from 'js-yaml';: We import the js-yaml library, which provides a function to parse YAML strings.
  2. import * as json from 'json';: We import the json library, which provides functions to work with JSON data.
  3. const yamlString = '...': We define a YAML string with some sample data.
  4. const jsonData = yaml.load(yamlString);: We use the yaml.load() function to parse the YAML string into a JavaScript object.
  5. const jsonString = JSON.stringify(jsonData, null, 2);: We use the JSON.stringify() function to convert the JavaScript object to a JSON string, with indentation for readability.
  6. console.log(jsonString);: We log the resulting JSON string to the console.

Handling Edge Cases

Empty/Null Input

When handling empty or null input, we should check for these cases and provide a meaningful error message:

if (!yamlString) {
  throw new Error('Input YAML string is empty or null');
}

Invalid Input

When handling invalid input, we should catch any errors thrown by the yaml.load() function:

try {
  const jsonData = yaml.load(yamlString);
  // ...
} catch (error) {
  console.error('Error parsing YAML:', error);
}

Large Input

When handling large input, we should consider using a streaming approach to avoid loading the entire YAML string into memory:

import { Readable } from 'stream';
import * as yaml from 'js-yaml';

const yamlStream = new Readable({
  read() {
    this.push(yamlString);
    this.push(null);
  },
});

yamlStream
  .pipe(yaml.parser())
  .on('data', (chunk) => {
    console.log(chunk);
  })
  .on('error', (error) => {
    console.error('Error parsing YAML:', error);
  });

Unicode/Special Characters

When handling Unicode or special characters, we should ensure that the js-yaml library is configured to handle these characters correctly:

const yamlOptions = {
  noRefs: true,
  noDefaults: true,
  noCompatMode: true,
};

const jsonData = yaml.load(yamlString, yamlOptions);

Common Mistakes

Mistake 1: Not Handling Errors

// Wrong
const jsonData = yaml.load(yamlString);

// Correct
try {
  const jsonData = yaml.load(yamlString);
  // ...
} catch (error) {
  console.error('Error parsing YAML:', error);
}

Mistake 2: Not Checking for Empty/Null Input

// Wrong
const jsonData = yaml.load(yamlString);

// Correct
if (!yamlString) {
  throw new Error('Input YAML string is empty or null');
}

Mistake 3: Not Using Streaming for Large Input

// Wrong
const jsonData = yaml.load(yamlString);

// Correct
import { Readable } from 'stream';
import * as yaml from 'js-yaml';

const yamlStream = new Readable({
  read() {
    this.push(yamlString);
    this.push(null);
  },
});

Performance Tips

  1. Use streaming for large input: When handling large YAML strings, use a streaming approach to avoid loading the entire string into memory.
  2. Use caching: If you need to convert the same YAML string multiple times, consider caching the result to avoid repeated parsing.
  3. Optimize YAML string formatting: Use tools like yaml-lint to optimize YAML string formatting and reduce parsing time.

FAQ

Q: Can I use this approach for converting JSON to YAML?

A: Yes, you can use the js-yaml library to convert JSON to YAML by using the yaml.dump() function.

Q: How do I handle circular references in YAML?

A: You can use the noRefs option when parsing YAML to ignore circular references.

Q: Can I use this approach for converting YAML to JSON in a browser?

A: Yes, you can use the js-yaml library in a browser by including the library in your HTML file.

Q: How do I handle Unicode characters in YAML?

A: You can use the noCompatMode option when parsing YAML to handle Unicode characters correctly.

Q: Can I use this approach for converting large YAML files?

A: Yes, you can use the streaming approach to handle large YAML files.

AI agent tools available. The CodeTidy MCP Server gives Claude, Cursor, and other AI agents access to 60+ developer tools. One command: npx @codetidy/mcp