naiveBayes naiveBayes - 25 days ago 6x
Java Question

Remove the dash present before the key value pair in a YAML file

It is known that the dash(-) in a yaml file before the key value pair is necessary to show that it is separate block(it is what I think). Figure 1 shows the yaml I'm generating using YamlBeans jar. For my codebase can't be changed, I have to somehow create the YAMLs as shown in Figure 2 (a tab is appended in each line in yaml file) or remove the dash is removed. You can clearly observe that there are only two thin vertical lines in Figure 1 but three thin vertical lines in Figure 2 which shows the alignment of the blocks.

What I want to achieve is to remove that dash from the first block (at the child field) from the file. Using a Yaml file reader and writer always introduces the dash.
Please help.


glancing quick at (but admittedly not being familiar with) YamlBeans, it doesn't look like it's easy to subclass the behavior of the Emitter. One option though is to generate a temporary form in memory, then manipulate the results when writing out to a file. For example

    // let YamlWriter write its contents to an in-memory buffer
    StringWriter temp = new StringWriter();
    YamlWriter yamlOut = new YamlWriter(temp);

    // then dump the in-memory buffer out to a file, manipulating lines that
    // start with a dash
    PrintWriter out = new PrintWriter(new FileWriter(new File("someoutput.dat")));
    LineNumberReader in = new LineNumberReader(new StringReader(temp.toString()));
    String line;
    while ((line = in.readLine()) != null) {
        if (line.startsWith("-")) {
            line = line.substring(1);

my specifics may be off, but hopefully the approach of doing simple manipulations of a temporary copy is clear enough.

If i were personally doing this, i'd probably write a custom subclass of and do the manipulation on the fly (but i haven't gone through YamlWriter/Emitter in enough detail to provide an example on how to do that)