Parsing YAML Front matter in Java

I need to parse YAML Front Matter in java as jekyll , so I understood in the source code and found this , but I can’t interpret it (I don’t know many rubies).

So my question is: how to parse YAML Front Matter in java?

I have snakeyaml in my classpath and I would parse the YAML Front Matter from the markdown file for which I use pegdown

+6
source share
3 answers
 void parse(Reader r) throws IOException { BufferedReader br = new BufferedReader(r); // detect YAML front matter String line = br.readLine(); while (line.isEmpty()) line = br.readLine(); if (!line.matches("[-]{3,}")) { // use at least three dashes throw new IllegalArgumentException("No YAML Front Matter"); } final String delimiter = line; // scan YAML front matter StringBuilder sb = new StringBuilder(); line = br.readLine(); while (!line.equals(delimiter)) { sb.append(line); sb.append("\n"); line = br.readLine(); } // parse data parseYamlFrontMatter(sb.toString()); parseMarkdownOrWhatever(br); } 

To get a Reader , you probably need a FileReader or InputStreamReader .

+7
source

Good, as your comment clarified what your question is:

The Yamal front is everything that is inside the lines with three strokes ( --- ). YAML Front matter ALWAYS at the beginning of a file.

So, you just need to analyze the file and extract the original YAML information from the very beginning of the file. You can analyze it using a machine or RegEx. It really is up to you. It is always structured in the same way:

  ---
 some yaml here
 ---
 Markdown / textile / HTML contents of file
+2
source

If you are only interested in the initial question, you can use the SnakeYaml loadAll method:

 Object yamlFrontMatter(Yaml yaml, InputStream in) { return yaml.loadAll().iterator().next(); } 

SnakeYaml will only read the first structure of the yaml (front) and ignore the final non-yaml text.

Unfortunately, SnakeYaml does not have an elegant way to display the remaining text, so if you want to analyze both the front and the body at the same time, there is no advantage in this approach: - (

+2
source

Source: https://habr.com/ru/post/921909/


All Articles