Skip to content
Advertisement

Missing double quotes for the required field using Snake Yaml

i am trying to read a Yaml template and replace certain fields in the template dynamically and create a new Yaml file. My resultant yaml file should reflect the template in all aspects including the double quotes. But I am missing double quotes for the required fields when I use snake yaml. Can anyone please suggest to resolve this issue?

Example :

My yaml template is as shown below:

JavaScript

I am reading the above template and replacing the required fields dynamically as shown below.

JavaScript

Now I am replacing the required fields as shown below

JavaScript

I am expecting output as shown below

Expected Output :

JavaScript

But I am actually getting output as below

JavaScript

My problem here is, I am missing the double quotes for “id” node in the new yaml file. When I use, options.setDefaultScalarStyle(ScalarStyle.DOUBLE_QUOTED), I am getting all fields double quoted which is not required. I need double quotes for id field only. Can anyone please advice to resolve this issue.

Thanks

Advertisement

Answer

If your input is a template, it might be better to use a templating engine. As simple example, MessageFormat would allow you to write id: "{0}" and then interpolate the actual value into it, keeping the double quotes. You could use more sophisticated templating depending on your use-case.


That being said, let’s look at how to do it with SnakeYAML:

If you want to control how a single item is rendered as scalar, you have to define a class like this:

JavaScript

And then create a custom representer for it:

JavaScript

Modify your code to use the new class:

JavaScript

And finally, instruct SnakeYAML to use your representer:

JavaScript

This should do it.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement