Search code examples
pyyaml

Yaml File escape characters in multiline string


I want to use \n character in multiline string but YAML doesn't allow me to use \n character. How can I use \n character.

My YAML:

treeroot:
    branch1:
        name: >
            hello my friend\n how are you ?
            i am fine and you ?\n
            yes\nthanks
        branch1-1:
            name: Node 1-1
    branch2:
        name: Node 2
        branch2-1:
            name: Node 2-1

I know, we can use \n character in single line mode but I want use it in multiline.


Solution

  • There is no such thing as 'single-line' mode in YAML. You have scalars that represent strings and they can be plain (no quotes), single and double quoted. Apart from that, in block-style, you have literal and folded style.

    Literal and folded style are always multiline (assuming you count the line with the | resp. the >), but the other scalars can be multiline as well. In the later case double new-lines in the string are transformed into newlines and other new-lines into spaces. Since escaping with backslash is only allowed in double quoted strings the following YAML is what you need to use:

    treeroot:
        branch1:
            name: "hello my friend\n how are you ?
                i am fine and you ?\n
                yes\nthanks"
            branch1-1:
                name: Node 1-1
        branch2:
            name: Node 2
            branch2-1:
                name: Node 2-1
    

    The value for the first key 'name' is the same as if specified as

    "hello my friend\n how are you ? i am fine and you ?\n yes\nthanks"