[英]In ruamel.yaml, how do I emit a ScalarEvent with the literal string "null"?
我正在使用 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'
您的代码不完整,但由于您在映射事件上设置了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}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.