首页 > 解决方案 > 在 ruamel.yaml 中,如何使用文字字符串“null”发出 ScalarEvent?

问题描述

我正在使用 ruamel.yaml 发出一系列事件来创建自定义 YAML 文件格式混合流样式。

我发现自己无法发出值为“null”的 ScalarEvent,因此它在 YAML 文件中显示为字符串“null”,而不是 YAML 关键字 null。

以代码形式,如果我尝试

dumper = yaml.Dumper(out_file,  width=200)
param = 'field'
param_value = 'null'
dumper.emit(yaml.MappingStartEvent(anchor=None, tag=None, implicit=True, flow_style=True))
dumper.emit(yaml.ScalarEvent(anchor=None, tag=None, implicit=(True, True), value=param))
dumper.emit(yaml.ScalarEvent(anchor=None, tag=None, implicit=(True, True), value=param_value))
dumper.emit(yaml.MappingEndEvent())

我明白了

field: null

而我想看看

field: 'null'

标签: pythonyamlruamel.yaml

解决方案


您的代码不完整,但是由于您设置flow_style=True了映射事件,因此您没有获得显示的代码,也永远不会获得您想要的输出。

如果您想走这条路,请查看代码中唯一ruamel.yaml发出ScalarNode. 它在serializer.py

            self.emitter.emit(
                ScalarEvent(
                    alias,
                    node.tag,
                    implicit,
                    node.value,
                    style=node.style,
                    comment=node.comment,
                )
            )

从那里你会发现你需要添加style 参数。进一步挖掘将显示这应该是一个单字符串,在您的情况下是单引号(“ '”),以强制使用单引号标量。

import sys
import ruamel.yaml as yaml

dumper = yaml.Dumper(sys.stdout,  width=200)
param = 'field'
param_value = 'null'
dumper.emit(yaml.StreamStartEvent())
dumper.emit(yaml.DocumentStartEvent())
# !!!! changed flow_style in the next line
dumper.emit(yaml.MappingStartEvent(anchor=None, tag=None, implicit=True, flow_style=False))
dumper.emit(yaml.ScalarEvent(anchor=None, tag=None, implicit=(True, True), value=param))
# added style= in next line
dumper.emit(yaml.ScalarEvent(anchor=None, tag=None, implicit=(True, True), style="'", value=param_value))
dumper.emit(yaml.MappingEndEvent())
dumper.emit(yaml.DocumentEndEvent())
dumper.emit(yaml.StreamEndEvent())

这给了你想要的:

field: 'null'

但是,我认为您正在使您的生活变得比必要的更加困难。ruamel.yaml确实在往返过程中保留了流式,并且您创建了一个功能数据结构并转储它,而不是恢复到使用事件驱动转储器:

import sys
import ruamel.yaml

yaml_str = """\
a:
   - field: 'null'
     x: y
   - {field: 'null', x: y}
"""

yaml = ruamel.yaml.YAML()
data = yaml.load(yaml_str)
for i in range(2):
    data["a"].append(ruamel.yaml.comments.CommentedMap([("a", "b"), ("c", "d")]))
data["a"][-1].fa.set_flow_style()
yaml.dump(data, sys.stdout)

这给出了:

a:
- field: 'null'
  x: y
- {field: 'null', x: y}
- a: b
  c: d
- {a: b, c: d}

推荐阅读