json-parser-yaml-converter
Version:
Enhanced JSON Parser with verbose error messages and JSON to YAML conversion
49 lines (43 loc) • 1.53 kB
JavaScript
/**
* This module contains the function jsonToYaml that converts a JSON file to a YAML file.
*
* @module yamlConverter
*/
;
import { jsonParse } from './index.js';
import { writeFileSync } from 'fs';
/**
* Converts a JSON file to a YAML file.
* @param {string} jsonFile JSON file to convert.
* @param {string} yamlFile YAML file to output.
* @returns {void}
* @throws {Error} If the JSON file could not be converted to YAML.
*/
function jsonToYaml(jsonFile, yamlFile) {
const JSON_AST = jsonParse(jsonFile, true);
const YAML = astToYamlString(JSON_AST);
writeFileSync(yamlFile, YAML);
}
/**
* Converts a JSON AST to a YAML string.
* @param {Object} ast AST to convert.
* @param {number} indent Current indentation level.
* @returns {string} The YAML string.
*/
function astToYamlString(ast, indent = 0) {
let yamlString = '';
if (ast.type === 'object') {
yamlString += ast.properties.map((pair) => {
return ' '.repeat(indent) + pair.key + ': ' + astToYamlString(pair.value, indent + 2);
}).join('\n');
return yamlString.length === 0 ? '{}' : indent === 0 ? yamlString : '\n' + yamlString;
}
if (ast.type === 'array') {
yamlString += ast.elements.map((element) => {
return ' '.repeat(indent) + '- ' + astToYamlString(element, indent + 2);
}).join('\n');
return yamlString.length === 0 ? '[]' : indent === 0 ? yamlString : '\n' + yamlString;
}
return String(ast.value);
}
export { jsonToYaml };