PyYAML dump format

后端 未结 3 918
耶瑟儿~
耶瑟儿~ 2020-11-30 03:08

I know there are a few questions about this on SO, but I couldn\'t find what I was looking for.

I\'m using pyyaml to read (.load()) a .yml

3条回答
  •  迷失自我
    2020-11-30 03:46

    In my case, I want " if value contains a { or a }, otherwise nothing. For example:

     en:
       key1: value is 1
       key2: 'value is {1}'
    

    To perform that, copy function represent_str() from file representer.py in module PyYaml and use another style if string contains { or a }:

    def represent_str(self, data):
        tag = None
        style = None
        # Add these two lines:
        if '{' in data or '}' in data:
            style = '"'
        try:
            data = unicode(data, 'ascii')
            tag = u'tag:yaml.org,2002:str'
        except UnicodeDecodeError:
            try:
                data = unicode(data, 'utf-8')
                tag = u'tag:yaml.org,2002:str'
            except UnicodeDecodeError:
                data = data.encode('base64')
                tag = u'tag:yaml.org,2002:binary'
                style = '|'
        return self.represent_scalar(tag, data, style=style)
    

    To use it in your code:

    import yaml
    
    def represent_str(self, data):
      ...
    
    yaml.add_representer(str, represent_str)
    

    In this case, no diffences between keys and values and that's enough for me. If you want a different style for keys and values, perform the same thing with function represent_mapping

提交回复
热议问题