Skip to content

Instantly share code, notes, and snippets.

@MikeRalphson
Created January 23, 2021 14:36
Show Gist options
  • Save MikeRalphson/036324d1ea1d95e0da5d3243f8f0b06c to your computer and use it in GitHub Desktop.
Save MikeRalphson/036324d1ea1d95e0da5d3243f8f0b06c to your computer and use it in GitHub Desktop.
Parse YAML preserving comments in a given JSON property
const yaml = require('yaml');
const recurse = require('reftools/lib/recurse.js').recurse;
const ast = yaml.parseDocument(inputStr);
recurse(ast,{},function(obj,key,state){
let comment;
if (obj[key] && obj[key].commentBefore) {
comment = obj[key].commentBefore;
}
if (obj[key] && obj[key].comment) {
comment = obj[key].comment;
}
if (comment && Array.isArray(state.parent)) {
let existing = state.parent.find(function(e,i,a){
if (e.key.value === '$comment') return true;
});
if (existing) {
existing.value.value += '\n' + comment;
}
else {
state.parent.push(ast.createPair('$comment',comment));
}
}
});
return ast.toJSON();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment