Search code examples
pythonyamlpyyaml

Load element as string when it ends with a colon


I have a YAML document where some values end with a colon, something like:

foo:
  - bar
  - baz::

When I load the document with yaml.load, the baz:: element gets converted to a dictionary {'baz:' : ''}. However, I would like to read it as string.

I've tried loading the file with the yaml.BaseLoader, however this did not help. Is there a way to specify that the elements should not be converted to a dict?


Solution

  • Q: "Is there a way to specify that the elements should not be converted to a dict?"

    Just quote them.

    Whereby for

    foo:
      - bar
      - baz::
    

    an output result will become

    foo:
      - bar
      - 'baz:': null
    

    for

    bar:
      - foo
      - "foz::"
    

    it will stay with

    bar:
      - foo
      - 'foz::'
    

    Similar Q&A