如何通过ruamel.yaml进行转储时如何在yaml文件中保留空值 [英] how to keep null value in yaml file while dumping though ruamel.yaml

查看:376
本文介绍了如何通过ruamel.yaml进行转储时如何在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)可以表示为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值没有消失,使用RoundTripDump时,ruamel.yamlnull的默认表示只是不同地表示.如果再次加载该输出,您将再次获得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中创建不同的类(NULLNullnull等)来获得更精细的控制,并且每个类具有不同的表示符(与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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆