Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I control yaml indentation using SnakeYaml during dumping?

Tags:

java

snakeyaml

I am using snakeyaml library to parse yaml files, and dump it later from xml. I was wondering if there is any way to control final yaml indentation. For example, list in final file will look like this:

list:
- "first item"
- "second item"

I would like add some spaces before items of list. Final result should like like:

list:
   - "first item"
   - "second item"

I see there is possibility to add custom resolvers and representers. But neither let me to add extra spaces. I've seen that in ScalarNode class, there are marks which contain info about starting column and ending column, but those are used only for logging purpose. Does anyone know solution for such scenario?

like image 992
Adrian Kaczmarek Avatar asked Aug 30 '19 14:08

Adrian Kaczmarek


People also ask

Is YAML sensitive to indentation?

Indentation. The suggested syntax for YAML files is to use 2 spaces for indentation, but YAML will follow whatever indentation system that the individual file uses.

Does YAML use indentation?

Indentation is meaningful in YAML. Make sure that you use spaces, rather than tab characters, to indent sections. In the default configuration files and in all the examples in the documentation, we use 2 spaces per indentation level. We recommend you do the same.

What is SnakeYAML used for?

SnakeYAML allows you to read a YAML file into a simple Map object or parse the file and convert it into a custom Java object. Depending on your requirements you can decide in which format you want to read your YAML files.

What does indent mean in YAML?

In YAML block styles, structure is determined by indentation. In general, indentation is defined as a zero or more space characters at the start of a line. To maintain portability, tab characters must not be used in indentation, since different systems treat tabs differently.


2 Answers

DumperOptions.setIndicatorIndent() will do what you need.

like image 107
Andrey Avatar answered Nov 14 '22 23:11

Andrey


For apply the indentation required apply next configuration:

DumperOptions options = new DumperOptions();
options.setIndent(2);
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
options.setIndicatorIndent(2);
options.setIndentWithIndicator(true);

Where the properties IndicatorIndent and IndentWithIndicator apply this format output.

like image 37
sercheo_87 Avatar answered Nov 15 '22 00:11

sercheo_87