Created
January 23, 2021 14:36
-
-
Save MikeRalphson/036324d1ea1d95e0da5d3243f8f0b06c to your computer and use it in GitHub Desktop.
Parse YAML preserving comments in a given JSON property
This file contains 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 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