pyyaml: dumping without tags

前端 未结 5 1990
囚心锁ツ
囚心锁ツ 2021-01-30 19:45

I have

>>> import yaml
>>> yaml.dump(u\'abc\')
\"!!python/unicode \'abc\'\\n\"

But I want

>>> import         


        
5条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-30 20:21

    How about this:

    def unicode_representer(dumper, uni):
        node = yaml.ScalarNode(tag=u'tag:yaml.org,2002:str', value=uni)
        return node
    
    yaml.add_representer(unicode, unicode_representer)
    

    This seems to make dumping unicode objects work the same as dumping str objects for me (Python 2.6).

    In [72]: yaml.dump(u'abc')
    Out[72]: 'abc\n...\n'
    
    In [73]: yaml.dump('abc')
    Out[73]: 'abc\n...\n'
    
    In [75]: yaml.dump(['abc'])
    Out[75]: '[abc]\n'
    
    In [76]: yaml.dump([u'abc'])
    Out[76]: '[abc]\n'
    

提交回复
热议问题