How to preserve newline character in YAML property value?

I dealt with a particular use case in my project.

I had to fetch a string with newline characters from a yaml property file.

The string value was something like this:

quote: “I am Bond \n James Bond”

The problem was when I fetched this quote property in my code , it got modified into this :

“I am Bond \n\n James Bond”

I had written the key: value pair like this in the yaml property file :

quote: 'I am Bond\n James Bond'

YAML was appending backslash character to the newline character but I wanted that .

So I researched and found out that YAML doesn’t backslash newline character if you use the character “|” after the key (“quote” in our example) like this :

quote: |
       I am Bond
       James Bond

As you see you first enter the character “|”

And then enter a line break

Then you enter the first sentence ( I am Bond)

And then the next sentence in the next line (James Bond)

This is equivalent to the string :

"I am Bond\n James Bond"

This style is called literal style by YAML.

This style treats every character as content and does not escape any restricted characters.






Leave a Reply

%d bloggers like this: