Validating values in YAML files across collection Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Validating values in YAML files across collection without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I’m using Node (https://eemeli.org/yaml/) to parse a YAML configuration files which looks like so:

items:
  - name: item 1
    value: 25
  - name: item 2
    value: 25
  - name: item 3
    value: 50

What I’d like to do is assert the value numbers all add up to 100 when parsing the document.

Should I be running this validation after parsing the YAML

eg:

data = YAML.parse(recipe)
validate(data)

Or is there a better way of doing this using the YAML library directly when loading the document?

Thanks in advance for your help!

Answer

You’re better of parsing the YAML first, then going through the resulting data. So, in this case, the parsed data would look something like:

data = {
    items: [
        {name: 'item 1', value: 25},
        {name: 'item 2', value: 25},
        ...
    ]
}

So, you can just loop through the values:

let total = 0;

data.items.map((item) => {
    total += item.value;
});

if (total !== 100) {
    ...
}
We are here to answer your question about Validating values in YAML files across collection - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji