JSON to YAML

Convert a JSON string to YAML format.

Code

Utilities
const toYaml = (obj, indent = 0) => {
  const pad = '  '.repeat(indent);
  if (Array.isArray(obj)) {
    return obj.map(v => `${pad}- ${typeof v === 'object' ? '\n' + toYaml(v, indent + 1) : v}`).join('\n');
  }
  if (typeof obj === 'object' && obj !== null) {
    return Object.entries(obj).map(([k, v]) => {
      if (typeof v === 'object') return `${pad}${k}:\n${toYaml(v, indent + 1)}`;
      return `${pad}${k}: ${v}`;
    }).join('\n');
  }
  return `${pad}${obj}`;
};
return toYaml(JSON.parse(json));

Parameters

JSON string to convert.

Browser·fetch() may be limited by CORS

More JavaScript Snippets