Search code examples
pythonyamldumppyyamlruamel.yaml

Dump object into yaml without quotes


I had some object that I want to turn into yaml, the only thing is that I need to be able to put "!anything" without quotes into it.

When I try it with pyyaml I end up with '!anything' inside my yaml file.

I've already tried using ruamel.yaml PreservedScalarString and LiteralScalarString. And it kind of works, but not in the way that I need to work. The thing is I end up with yaml that looks like this:

10.1.1.16:
            text: '1470814.27'
            confidence: |-
              !anything

But I don't need this |- symbol.

My goal is to get yaml like this:

10.1.1.16:
            text: '1470814.27'
            confidence: !anything

Any ideas how I can achieve that?


Solution

  • To dump a custom tag, you need to define a type and register a representer for that type. Here's how to do it for scalars:

    import yaml
    
    class MyTag:
      def __init__(self, content):
        self.content = content
    
      def __repr__(self):
        return self.content
    
      def __str__(self):
        return self.content
    
    def mytag_dumper(dumper, data):
      return dumper.represent_scalar("!anything", data.content)
    
    yaml.add_representer(MyTag, mytag_dumper)
    
    print(yaml.dump({"10.1.1.16": {
        "text": "1470814.27",
        "confidence": MyTag("")}}))
    

    This emits

    10.1.1.16:
      confidence: !anything ''
      text: '1470814.27'
    

    Note the '' behind the tag, which is the tagged scalar (no, you can't get rid of it). You can tag collections as well but you'll need to use represent_sequence or represent_mapping accordingly.