John W John W - 3 months ago 29
YAML Question

Can I anchor individual items in a YAML collection?

How can I write the Books collection so that I can anchor an individual item? This document is invalid.

Books:
- Title: The Cat in the Hat &catInTheHat
Author: Dr. Seuss
- Title: Harry Potter
Author: JK Rowling
People:
- Name: Bill
FavoriteBook: *catInTheHat
- Name: Edna

Answer

Yes you can, but in your example you don't have an anchor, and since you have an alias without a corresponding anchor, you get an error (and you should because that is not allowed).
What you do have, is a scalar string The Cat in the Hat &catInTheHat that has an ampersand somewhere in the middle.
If you want to define an anchor you need to put that before the actual item (scalar, sequence, mapping).

If you just want to alias the scalar string The Cat in the Hat (which is the value for Title) for FavoriteBook you can do:

Title: &catInTheHat The Cat in the Hat 
Author: Dr. Seuss

With that, if after parsing you access the value for FavoriteBook from the first element of the sequence that is the value for the toplevel key People (in Python: data['People'][0]['FavoriteBook']) you get the string "The Cat in the Hat".

If you want the first element of the sequence that is the values for Books you would have to do:

Books:
  - &catInTheHat 
    Title: The Cat in the Hat 
    Author: Dr. Seuss
  - Title: Harry Potter
    Author: JK Rowling

Then you actually get the representation of mapping (dict/hash/map depending on your programming language) from which you then directly can retrieve both title and author.

Please note that all the YAML parsers I have worked with "resolve" the alias if it refers to an scalar (string, integer etc). Dumping the data represented from the YAML source, results in losing the anchor and alias. For collections (sequences, mappings), this is more often not the case.