Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.6k views
in Technique[技术] by (71.8m points)

python - ruamel.yaml - how to output null instead of !!null '' when default_flow_style=None

Using ruamel.yaml in Python, if I dump with the SafeRepresenter or RoundTripRepresenter and default_flow_style the default, null is represented as expected.

from ruamel.yaml import YAML
yaml = YAML(typ='rt')
yaml.dump({'key1': None, 'url': 'https://lala/', 'key2': None}, sys.stdout)

key1:
url: https://lala/
key2:

However, if I change the default_flow_style to None, the representer for null seems to be ignored and instead null is represented as !!null '' eg.

from ruamel.yaml import YAML
yaml = YAML(typ='rt')
yaml.default_flow_style = None
yaml.dump({'key1': None, 'url': 'https://lala/', 'key2': None}, sys.stdout)


key: {key1: !!null '', url: https://lala/, key2: !!null ''}

Setting the representer for null explicitly makes no difference eg.

SafeRepresenter.add_representer(type(None), RoundTripRepresenter.represent_none)

I tried the above, but output for null when using the SafeRepresenter instead of the RoundTripRepresenter was still !!null '' when using default_flow_style=None.

How do I output null instead of !!null '' when using default_flow_style=None directly from ruamel.yaml rather than doing postprocessing on its output (eg. a find replace)?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I see two possible solutions.

The easiest solution is to use typ='safe' instead of typ='rt'. This is what I generally do , but if you're relying on ruamel.yaml's ability to preserve things like comments, this isn't an option.

You can create a representer for None values like this:

def represent_none(self, data):
    return self.represent_scalar('tag:yaml.org,2002:null', 'null')

Which will print out your None values as desired:

>>> import sys
>>> from ruamel.yaml import YAML
>>> yaml = YAML(typ='rt')
>>> yaml.default_flow_style = None
>>>
>>> def represent_none(self, data):
...     return self.represent_scalar('tag:yaml.org,2002:null', 'null')
...
>>> yaml.representer.add_representer(type(None), represent_none)
>>> yaml.dump({'key1': None, 'url': 'https://lala/', 'key2': None}, sys.stdout)
{key1: null, url: https://lala/, key2: null}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...