AnswerBun.com

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

Stack Overflow Asked on January 27, 2021

1 Answers

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!

Related Questions

NiFi Consume kafka sasl_plaintext issue

1  Asked on February 13, 2021 by varun_rathinam

       

Clock divider in vhdl from 100MHz to 1Hz code

2  Asked on February 13, 2021 by mariaaaa

     

Inconsistent Paging in ASP.NET CORE

0  Asked on February 13, 2021 by addsw

       

Nuxt.js: can’t generate routes

3  Asked on February 12, 2021 by drake035

     

set year to the x labels in matplotlib

1  Asked on February 12, 2021 by nargento

     

Proper way to use Vuex with child components

1  Asked on February 12, 2021 by luma

     

is DRAM(main memory) a character device?

0  Asked on February 11, 2021 by jonggyu-park

   

How to declare a function that accepts a typed array parameter

1  Asked on February 11, 2021 by zentrunix

 

Loop nested array and return values by index

4  Asked on February 11, 2021 by jordan-starrk

   

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved.