如何在ruamel.yaml生成YAML文件时移除!!omap标记?
问题
我使用ruamel.yaml库编写YAML文件,代码如下:
yaml1 = ruamel.yaml.YAML() yaml1.preserve_quotes = True with open('output.yaml', "wb") as fp: yaml1.dump(file, fp)
运行时file为ordereddict结构:
ordereddict([('formatVersion', '0.11'), ('deviceDescription', 'test Master-File'), ('strings', [ordereddict([('name', 'label_1'), ('en', 'test'), ('es', 'test'), ('de', 'test'), ('fr', 'test'), ('it', 'test'), ('ru', 'test'), ('zh', 'test')]), ordereddict([('name', 'label_2'), ('en', 'test'), ('es', 'test'), ('de', 'test'), ('fr', 'test'), ('it', 'test'), ('ru', 'test'), ('zh', 'test')])])])
我期望生成无!!omap标记的正常嵌套YAML格式,但实际生成的每个字典前都带有!!omap标记,请问如何去除该标记?
解决方法
ruamel.yaml默认会把ordereddict序列化为带!!omap标记的有序映射,要去掉这个标记,有两种实用方案:
方案一:转换为ruamel.yaml原生的CommentedMap
CommentedMap是ruamel.yaml内置的有序字典类型,序列化时不会生成!!omap标记。可以递归将所有ordereddict转换为CommentedMap:
from ruamel.yaml import YAML, CommentedMap from collections import OrderedDict def convert_to_commentedmap(data): if isinstance(data, OrderedDict): cm = CommentedMap() for key, value in data.items(): cm[key] = convert_to_commentedmap(value) return cm elif isinstance(data, list): return [convert_to_commentedmap(item) for item in data] else: return data # 转换原ordereddict数据 processed_data = convert_to_commentedmap(file) yaml1 = ruamel.yaml.YAML() yaml1.preserve_quotes = True with open('output.yaml', "wb") as fp: yaml1.dump(processed_data, fp)
方案二:自定义序列化规则
通过注册自定义representer,让ruamel.yaml把ordereddict当作标准映射处理,同时保留键的顺序:
from ruamel.yaml import YAML from collections import OrderedDict yaml1 = ruamel.yaml.YAML() yaml1.preserve_quotes = True # 注册ordereddict的自定义序列化逻辑 def ordered_dict_serializer(dumper, data): return dumper.represent_mapping('tag:yaml.org,2002:map', data.items()) yaml1.representer.add_representer(OrderedDict, ordered_dict_serializer) with open('output.yaml', "wb") as fp: yaml1.dump(file, fp)
两种方法都能生成不带!!omap标记的标准YAML,且完全保留原ordereddict的键顺序。
内容的提问来源于stack exchange,提问作者Marc
相关产品推荐
相关产品推荐

