Fresher
Fresher

Reputation: 97

How to validate yaml file from python script?

What's good way to validate yaml files ?

Any python script/module to validate yaml files ?

Valid

pipelines:
- name: some_name

Colour changes in pycharm

pipelines:
- name:check

Colour changes in pycharm

pipelines:
-name: check

For all above 3 cases, we can see change in colour of parameters. Can we handle these scenarios and any other extended validations of yaml file (or any standard schema) ?

Upvotes: 0

Views: 4836

Answers (1)

flyx
flyx

Reputation: 39778

All three examples are valid YAML. They just represent different data. What you probably want to do is to validate the actual structure against your expectation. Since there is no standard way to define the structure of a YAML document (like e.g. JSON Schema for JSON), there is no standard way to validate it.

That being said, you can use Python's typing package for defining the desired structure and then the typeguard package to validate the loaded structure against it:

from typing import TypedDict, List
from typeguard import check_type
import yaml

class PipelineItem(TypedDict):
  name: str

class MyYamlSchema(TypedDict):
  pipelines: List[PipelineItem]

file = """
pipelines:
- name: some_name
"""

data = yaml.safe_load(file)
check_type("data", data, MyYamlSchema)

This will raise an exception for the second and third case.

This solution requires Python 3.8.

Upvotes: 2

Related Questions