TransWikia.com

How to validate yaml file from python script?

Stack Overflow Asked on January 27, 2021

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) ?

One Answer

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.

Answered by flyx on January 27, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP