-
-
Save tristanwagner/1fc8a0652c5fa99abbaad3bcba9e08f6 to your computer and use it in GitHub Desktop.
Convert between YAML and JSON and vice versa
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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