如何通过ruamel.yaml进行转储时如何在yaml文件中保留空值 [英] how to keep null value in yaml file while dumping though ruamel.yaml
问题描述
我有YAML文件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
值没有消失,使用RoundTripDump
时,ruamel.yaml
中null
的默认表示只是不同地表示.如果再次加载该输出,您将再次获得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
如果您不喜欢这样做,则可以通过以下操作更改所有 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
等)来获得更精细的控制,并且每个类具有不同的表示符(与string
ruamel.yaml.scalarstring.py
中的子类用于以不同的方式表示字符串(双引号,单引号,文字块样式标量).问题是您不能子类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文件中保留空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!