Can I dump blank instead of null in yaml/pyyaml?

前端 未结 3 1033
灰色年华
灰色年华 2021-02-08 21:57

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

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

This returns Non

3条回答
  •  遇见更好的自我
    2021-02-08 22:51

    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.

提交回复
热议问题