您的代码不完整,但由于您在
映射事件,你没有得到你展示的代码,也永远不会得到你想要的输出。
如果你想走这条路,那么看代码中唯一的地方
其中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}