Instantly share code, notes, and snippets.

Embed
What would you like to do?
Convert between YAML and JSON and vice versa
const utils = require ("daveutils");
const yaml = require ("js-yaml");
function yamlIze (jsontext) {
var jstruct = JSON.parse (jsontext);
const delimiter = "---\n";
var text = jstruct.text;
delete jstruct.text;
var s = delimiter + yaml.safeDump (jstruct) + delimiter + text;
return (s);
}
function deYamlIze (data) {
const delimiter = "---\n";
var filetext = data.toString ();
if (utils.beginsWith (filetext, delimiter)) {
var frontmatter = utils.stringNthField (filetext, delimiter, 2);
var remainingtext = utils.stringDelete (filetext, 1, frontmatter.length + (2 * delimiter.length));
if (frontmatter.length > 0) {
var jstruct = yaml.safeLoad (frontmatter);
jstruct.text = remainingtext;
return (utils.jsonStringify (jstruct));
}
return (filetext);
}
return (filetext);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment