Validating a yaml document in python

前端 未结 10 2221
谎友^
谎友^ 2020-12-24 04:24

One of the benefits of XML is being able to validate a document against an XSD. YAML doesn\'t have this feature, so how can I validate that the YAML document I open is in th

10条回答
  •  佛祖请我去吃肉
    2020-12-24 05:12

    You can load YAML document as a dict and use library schema to check it:

    from schema import Schema, And, Use, Optional, SchemaError
    import yaml
    
    schema = Schema(
            {
                'created': And(datetime.datetime),
                'author': And(str),
                'email': And(str),
                'description': And(str),
                Optional('tags'): And(str, lambda s: len(s) >= 0),
                'setup': And(list),
                'steps': And(list, lambda steps: all('=>' in s for s in steps), error='Steps should be array of string '
                                                                                      'and contain "=>" to separate'
                                                                                      'actions and expectations'),
                'teardown': And(list)
            }
        )
    
    with open(filepath) as f:
       data = yaml.load(f)
       try:
           schema.validate(data)
       except SchemaError as e:
           print(e)
    

提交回复
热议问题