Search code examples
javayamlsnakeyaml

Dumping values with quotes with SnakeYaml


Having a simple yml file test.yml as follows

color: 'red'

I load and dump the file as follows

        final DumperOptions yamlOptions = new DumperOptions();
        yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);

        Yaml yaml = new Yaml(yamlOptions);


        Object result = yaml.load(new FileInputStream(new File("test.yml")));

        System.out.println(yaml.dump(result));

I expect to get

color: 'red'

However, the during the dump, the serializer leaves out the quotes and prints

color: red

How can I make the serializer to print the original quotes too?


Solution

  • How can I make the serializer to print the original quotes too?

    Not with the high-level API. Quoting the spec:

    The scalar style is a presentation detail and must not be used to convey content information, with the exception that plain scalars are distinguished for the purpose of tag resolution.

    The high-level API implements the whole YAML loading process, giving you only the content of the YAML file, without any information about presentation details, as required by the spec.

    That being said, you can use the low level API which preserves presentation details:

    final Yaml yaml = new Yaml();
    final Iterator<Event> events = yaml.parse(new StreamReader(new UnicodeReader(
            new FileInputStream(new File("test.yml"))).iterator();
    
    final DumperOptions yamlOptions = new DumperOptions();
    final Emitter emitter = new Emitter(new PrintWriter(System.out), yamlOptions);
    while (events.hasNext()) emitter.emit(events.next());
    

    However, be aware that even this will not preserve every presentation detail of your input (e.g. indentation and comments will not be preserved). SnakeYaml is not round-tripping and therefore unable to preserve the exact input layout.