Lakshmi S
Lakshmi S

Reputation: 21

How to auto edit Yaml file containing Anchors & Aliases using snakeyaml

I want to automate YAML file processing using snake YAML

Input:

_Function: &_Template
  Name: A
  Address: B

_Service: &_Service
  Problem1:
   <<: *_Template
  Problem2:
   <<: *_Template

Function.Service:
 Service1:
  <<: *_Service
 Service2:
  <<: *_Service

After Modifying the desired output is

_Function: &_Template
  Name: A
  Address: B

_Service: &_Service
  Problem1:
   <<: *_Template
  Problem2:
   <<: *_Template

Function.Service:
 Service1:
  <<: *_Service
 Service2:
  <<: *_Service
 Service2:
  <<: *_Service

Is it possible to modify file with out disturbing Anchors & aliases, I tried to read Yaml file and write it into different file, the output file contains Map objects in form key value pairs. But how to write output file with anchors & Aliases

Yaml yaml = new Yaml();
Map<String, Object> tempList = (Map<String, Object>)yaml.load(new FileInputStream(new File("/Users/Lakshmi/Downloads/test_input.yml")));
Yaml yamlwrite = new Yaml();
FileWriter writer = new FileWriter("/Users/Lakshmi/Downloads/test_output.yml");
yamlwrite.dump(tempList, writer);

If not snakeYaml, is there any language where-in we can auto modify yaml files without disturbing anchors & aliases.

Upvotes: 2

Views: 1882

Answers (2)

Sven D&#246;ring
Sven D&#246;ring

Reputation: 4368

With SnakeYAML 2.3, released in August 2024, it's finally possible to disable this behaviour in the DumperOptions.

dumperOptions.setDereferenceAliases​(true);

See the Javadoc for a little bit more information.

Upvotes: 0

flyx
flyx

Reputation: 39678

You can do this by iterating over the event stream instead of constructing a native value:

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());

The event stream is a traversal of the YAML file's structure where anchors & aliases are not resolved yet, see this diagram from the YAML spec:

You can insert additional events to add content. This answer shows how to do it in PyYAML; since SnakeYAML's API is quite similar, it should be no problem to rewrite this in Java. You can also write the desired additional values as YAML, load that as another event stream and then dump the content events of that stream into the main stream.

Upvotes: 1

Related Questions