我有以下格式的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()
答案 0 :(得分:0)
加载数据后,您可以递归遍历数据结构
您已加载以检查是否为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