javayamlsnakeyaml

SnakeYAML: Is it possible to get the anchor name of an object?


When I load the following document with SnakeYAML:

unit:
  &kg
  name: Kilogram

it returns a map with the following content:

{unit={name=Kilogram}}

The referencing with anchors works great in SnakeYAML but is it also possible to get the anchor names from the document?

Code snippet:

String text = "unit:\n  &kg\n  name: Kilogram\n";
System.out.println(new Yaml().load(text));  // -> {unit={name=Kilogram}}

Solution

  • SnakeYAML is originally based on PyYAML and that code based resolves the anchors by keeping a mapping from anchor names to objects it creates during the parsing. If the parser later encounters a reference, it looks up the name in the anchors and knows to create a link to the object created for the anchor.

    In PyYAML this mapping is in the code for the Composer object, the attribute is appropriately called anchors. SnakeYaml this is still called the same.

    What you need to do is walk over that mapping and compare the value with (a reference to) your object. If they match, the key belonging to the value was almost certainly the anchor name.


    In my python package ruamel.yaml, which is an update of PyYAML to YAML 1.2 I implemented a round_trip mode which preserves among other things comments and anchors. During construction I hang the comment and anchor information on the object to be created, which is easy to do in Python, but AFAIK not so easy in Java