簡體   English   中英

如何確保我的Yaml文件中沒有空值

[英]How to ensure there are no null values in my yaml file

我有以下格式的YAML文件:

name:
  - type1: abc
    type2: xyz
    type3: def
  - type1: jkl
    type2: 
    type3: pqr

我通過python解析YAML文件並讀取所有值。 如何報告丟失的條目?

**** Python代碼*****

    #read data from the config yaml file
    def read_yaml(file):
        with open(file, "r") as stream:
            try:
                config = yaml.safe_load(stream)
                # print(config)
            except yaml.YAMLError as exc:
                print(exc)
                print("\n")
        return config

    d = read_yaml("config.yaml")

這對我不起作用:

     for key,val in d.items():
          print("{} = {}".format(key,val))
          if not all([key, val]):
             print("missing entry")
             exit()

加載數據后,可以遞歸地遍歷加載的數據結構,以檢查是否有任何項目或值為None 這樣,您就不受固定結構的限制:

import sys
import ruamel.yaml

yaml_str = """\
name:
   - type1: abc
     type2: xyz
     type3: def
   - type1: jkl
     type2: 
     type3: pqr
"""

def check(d, prefix=None):
    if prefix is None:
        prefix = []
    if isinstance(d, dict):
        for k, v in d.items():
            if v is None:
                print('null value for', prefix + [k])
            else:
                check(v, prefix + [k])
    elif isinstance(d, list):
        for idx, elem in enumerate(d):
            if elem is None:
                print('null value for', prefix + [idx])
            else:
                check(elem, prefix + [idx])

yaml = ruamel.yaml.YAML(typ='safe')
data = yaml.load(yaml_str)
check(data)

這使:

null value for ['name', 1, 'type2']

或者,您可以讓解析器完成繁重的工作:

from ruamel.yaml.constructor import ConstructorError, SafeConstructor
import traceback

def no_null_allowed(self, node):
    raise ConstructorError(
        'while parsing input',
        node.start_mark,
        'null encountered',
        node.start_mark,
    )


SafeConstructor.add_constructor(
   u'tag:yaml.org,2002:null', no_null_allowed)

yaml = ruamel.yaml.YAML(typ='safe')
try:
    data = yaml.load(yaml_str)
except ConstructorError as e:
    traceback.print_exc(file=sys.stdout)

導致:

Traceback (most recent call last):
  File "/tmp/ryd-of-anthon/ryd-214/tmp_1.py", line 33, in <module>
    data = yaml.load(yaml_str)
  File "/opt/util/ryd/lib/python3.6/site-packages/ruamel/yaml/main.py", line 331, in load
    return constructor.get_single_data()
  File "/opt/util/ryd/lib/python3.6/site-packages/ruamel/yaml/constructor.py", line 108, in get_single_data
    return self.construct_document(node)
  File "/opt/util/ryd/lib/python3.6/site-packages/ruamel/yaml/constructor.py", line 118, in construct_document
    for _dummy in generator:
  File "/opt/util/ryd/lib/python3.6/site-packages/ruamel/yaml/constructor.py", line 691, in construct_yaml_map
    value = self.construct_mapping(node)
  File "/opt/util/ryd/lib/python3.6/site-packages/ruamel/yaml/constructor.py", line 418, in construct_mapping
    return BaseConstructor.construct_mapping(self, node, deep=deep)
  File "/opt/util/ryd/lib/python3.6/site-packages/ruamel/yaml/constructor.py", line 242, in construct_mapping
    value = self.construct_object(value_node, deep=deep)
  File "/opt/util/ryd/lib/python3.6/site-packages/ruamel/yaml/constructor.py", line 164, in construct_object
    data = constructor(self, node)
  File "/tmp/ryd-of-anthon/ryd-214/tmp_1.py", line 24, in no_null_allowed
    node.start_mark,
ruamel.yaml.constructor.ConstructorError: while parsing input
null encountered
  in "<unicode string>", line 6, column 12

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM