问题描述
我有 YAML 文件 site.yaml:
I have YAML file site.yaml:
Kvm_BLOCK:
ip_address: 10.X.X.X
property: null
server_type: zone
加载然后转储:
ruamel.yaml.dump(site_yaml, new_file, Dumper=ruamel.yaml.RoundTripDumper)
变成了
Kvm_BLOCK:
ip_address: 10.X.X.X
property:
server_type: zone
如何在属性块中保留这个 null 值
how to retain this null value in property block
推荐答案
YAML 1.2中的null值(构造为Python的None)可以表示为null、Null、NULL 和 ~,指定为 这里.
The null value in YAML 1.2 (constructed as Python's None) can be represented as null, Null, NULL and ~, as specified here.
另外:
内容为空的节点被解释为它们是具有空值的普通标量.此类节点通常被解析为空"值.
Nodes with empty content are interpreted as if they were plain scalars with an empty value. Such nodes are commonly resolved to a "null" value.
因此,您的 null 值并没有消失,它只是在使用 ruamel.yaml 时由 null 的默认表示不同地表示代码>RoundTripDump代码>.如果再次加载该输出,您将再次获得 None 作为键 property
Therefore your null value is not gone, it is just represented differently by the default representation for null in ruamel.yaml when using RoundTripDump. If you load that output again, you once more get a None as value for the key property
如果您不喜欢这样,您可以通过以下方式更改 all None/null 值的输出:
If that is not to your liking you can change the output for all None/null values by doing:
import sys
import ruamel.yaml
yaml_str = """
Kvm_BLOCK:
ip_address: 10.X.X.X
property: null
server_type: zone
"""
def my_represent_none(self, data):
return self.represent_scalar(u'tag:yaml.org,2002:null', u'NULL')
yaml = ruamel.yaml.YAML()
yaml.representer.add_representer(type(None), my_represent_none)
data = yaml.load(yaml_str)
yaml.dump(data, sys.stdout)
将转储:
Kvm_BLOCK:
ip_address: 10.X.X.X
property: NULL
server_type: zone
您可以通过在 Python 中创建不同的类(NULL、Null、null 等)并使用不同的表示器来获得更细粒度的控制对于它们中的每一个(与 ruamel.yaml.scalarstring.py 中的 string 子类用于以不同方式表示字符串的方式非常相似(双引号,单引用,文字块样式标量).问题是你不能继承 NoneType 所以这不像字符串标量那样容易透明地完成.
You can get finer grained control by creating different classes in Python (NULL, Null, null, etc. ) and have different representers for each of them (much in the same way that the string subclasses in ruamel.yaml.scalarstring.py are used to represent a string in different ways (double quoted, single quoted, literal block style scalar). The problem is that you cannot subclass NoneType so this is not so easily done transparently as with the string scalars.
这篇关于通过 ruamel.yaml 转储时如何在 yaml 文件中保留空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)