通过 ruamel.yaml 转储时如何在 yaml 文件中保留空值

2022-01-14 00:00:00 python pyyaml yaml ruamel.yaml

问题描述

我有 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)可以表示为nullNullNULL~,指定为 这里.

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 中创建不同的类(NULLNullnull 等)并使用不同的表示器来获得更细粒度的控制对于它们中的每一个(与 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.

相关文章