Tutorial :Escape an & (ampersand) at the start of a YAML entry?


An ampersand at the start of a YAML entry is normally seen as a label for a set of data that can be referenced later. How do you escape a legitimate ampersand at the start of a YAML entry. For example:

- news:
    news_text: “Text!’

I am looking to not have &ldquo be a label within the yaml file, but rather when I get parse the YAML file to have the news_text come back with the “ in the entry.


Just put quotes around the text

require 'yaml'    data = <<END  ---  - news:      news_text: "&ldquo;Text!&rsquo;"  END    puts YAML::load(data).inspect    # produces => [{"news"=>{"news_text"=>"&ldquo;Text!&rsquo;"}}]  


You probably can enclose the text in quotes:

---  - news:      news_text: "&ldquo;Text!&rsquo;"  

Besides, you can probably just as well use the proper characters there:

---  - news:      news_text: “Text!’  

Putting escapes specific to a totally different markup language into a document written in another markup language seems ... odd to me, somehow.


Or you could put the string on the next line, if you put a '>' or '|' at the spot where the string used to be. Using the '|' character your parser will keep your custom line breaks, while '>' turns it into one long string, ignoring line breaks.

- news:      news_text: >          &ldquo;Text!&rsquo;  


Putting the entire string in single quotes would do what you want:

---  - news:      news_text: '&ldquo;Text!&rsquo;'  

But, I think that any yaml library should be smart enough to do that for you?

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »