如何替换 ruamel.yaml 中的 NoneType 代表
How to replace the NoneType representer in ruamel.yaml
我正在使用由应用程序处理的 YAML 文件进行计算。此应用程序仅支持 ~
用于 None
赋值,但 ruamel.yaml
同时使用 ''
和 null
关键字。
例如:
from ruamel.yaml import YAML
yaml_example = """\
info:
value1: null
value2: [5, null, 12]
"""
yaml = YAML()
info = yaml.load(yaml_example)
with open('textfile.yaml', 'w') as file:
yaml.dump(info, file)
这会产生
info:
value1:
value2: [5, null, 12]
但是,我需要这样的输出:
info:
value1: ~
value2: [5, ~, 12]
如何使用 ~
获得输出?
我查看了以下问题,但未能成功将其应用于 ruamel.yaml
。
您必须更改空标记的表示者:
import sys
import ruamel.yaml
yaml_example = """\
info:
value1: null
value2: [5, null, 12]
"""
def _represent_none(self, data):
if len(self.represented_objects) == 0 and not self.serializer.use_explicit_start:
return self.represent_scalar('tag:yaml.org,2002:null', 'null')
return self.represent_scalar('tag:yaml.org,2002:null', "~")
ruamel.yaml.representer.RoundTripRepresenter.add_representer(type(None), _represent_none)
yaml = ruamel.yaml.YAML()
info = yaml.load(yaml_example)
yaml.dump(info, sys.stdout)
给出:
info:
value1: ~
value2: [5, ~, 12]
我正在使用由应用程序处理的 YAML 文件进行计算。此应用程序仅支持 ~
用于 None
赋值,但 ruamel.yaml
同时使用 ''
和 null
关键字。
例如:
from ruamel.yaml import YAML
yaml_example = """\
info:
value1: null
value2: [5, null, 12]
"""
yaml = YAML()
info = yaml.load(yaml_example)
with open('textfile.yaml', 'w') as file:
yaml.dump(info, file)
这会产生
info:
value1:
value2: [5, null, 12]
但是,我需要这样的输出:
info:
value1: ~
value2: [5, ~, 12]
如何使用 ~
获得输出?
我查看了以下问题,但未能成功将其应用于 ruamel.yaml
。
您必须更改空标记的表示者:
import sys
import ruamel.yaml
yaml_example = """\
info:
value1: null
value2: [5, null, 12]
"""
def _represent_none(self, data):
if len(self.represented_objects) == 0 and not self.serializer.use_explicit_start:
return self.represent_scalar('tag:yaml.org,2002:null', 'null')
return self.represent_scalar('tag:yaml.org,2002:null', "~")
ruamel.yaml.representer.RoundTripRepresenter.add_representer(type(None), _represent_none)
yaml = ruamel.yaml.YAML()
info = yaml.load(yaml_example)
yaml.dump(info, sys.stdout)
给出:
info:
value1: ~
value2: [5, ~, 12]