我可以在 yaml/pyyaml 中转储空白而不是 null 吗? [英] Can I dump blank instead of null in yaml/pyyaml?

查看:52
本文介绍了我可以在 yaml/pyyaml 中转储空白而不是 null 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 PyYAML,如果我在字典中读入一个空值的文件:

test_str = '''属性:第一的:第二个:值2'''

这会为键 first 返回 None:

<预><代码>>>>数据 = yaml.load(test_str)>>>数据{'attrs': {'second': 'value2', 'first': None}}

但是在写入时,None 值被替换为 null:

<预><代码>>>>打印(yaml.dump(数据,default_flow_style=False))属性:第一:空第二个:值2

有没有办法格式化转储输出以打印空白标量而不是 null?

解决方案

基于@Anthon 的 优秀答案,我被能够制定此解决方案:

def 表示_none(self, _):return self.represent_scalar('tag:yaml.org,2002:null', '')yaml.add_representer(类型(无),represent_none)

基于我对 PyYAML 代码的理解a>,为现有类型添加代表应该简单地替换现有代表.

这是一个全局更改,这意味着所有后续转储都使用空白.如果你的程序中一些不相关的其他代码依赖 None 以正常"方式表示,例如您导入并使用 PyYAML 的库,该库将不再以预期的方式/正确方式工作,在这种情况下,子类化是正确的方法.

Using PyYAML, if I read in a file with blank values in a dict:

test_str = '''
attrs:
  first:
  second: value2
'''

This returns None for the key first:

>>> data = yaml.load(test_str)
>>> data
{'attrs': {'second': 'value2', 'first': None}}

But when writing, the None value is replaced with null:

>>> print(yaml.dump(data, default_flow_style=False))
attrs:
  first: null
  second: value2

Is there a way to format the dump output to print a blank scalar rather than null?

Based on @Anthon's excellent answer, I was able to craft this solution:

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

yaml.add_representer(type(None), represent_none)

Based on my understanding of the PyYAML code, adding a representer for an existing type should simply replace the existing representer.

This is a global change and that means that all following dumps use a blank. If some unrelated other piece of code in your program relies on None to be represented in the "normal" way, e.g. a library that you import and that uses PyYAML as well, that library will no longer work in the exepected way/correctly, in that case subclassing is the correct way to go.

这篇关于我可以在 yaml/pyyaml 中转储空白而不是 null 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆