Create a JSON-to-Yaml converter that supports comments
This Issue is to track a sub-task related to gitlab-org/incubation-engineering/jamstack/meta#7 (moved).
In order to programatically create a yaml-file from interactive input fields I need a yaml.dump() method that supports the injection of comments into the resulting yaml.
It takes a valid JSON object and looks for special keys/strings and converts those to comments:
{
"foods": {
"#": "What to feed wild animals if they look like they are unable to feed themselves",
"cats": "milk",
"birds": ["seeds", "worms"],
"#|hedgehogs": "Although hedgehogs like cat food, they should never be fed with milk",
"hedgehogs": "cat food"
},
"predators": [
"Cats",
"Dogs",
"# Tigers are rather rare in europe.",
"Tigers"
]
}
Will become:
foods:
# What to feed wild animals if they look like they are unable to feed
# themselves
cats: milk
birds:
- seeds
- worms
# Although hedgehogs like cat food, they should never be fed with milk
hedgehogs: cat food
predators:
- Cats
- Dogs
# Tigers are rather rare in europe.
- Tigers
Rules:
Objects
- Generic comments in objects have the key
"#". They will be injected before the first child of the object. There can be only one generic comment per object. - Specific comments in objects have a key following the pattern
"#|<id>"with<id>corresponding to a key of another child of the object. These will be injected before that child.
Arrays
- Entries in the array that are strings and start with
#(including the space!) are determined to be comments and are injected as comments at the position they are inside the array.
Demo
Edited by Janis Altherr