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
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. Depending on the programming language and YAML parsers you use, the parser might "resolve" the alias if it refers to an scalar (string, integer etc) or not. 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 (i.e. they refer to the same collection object in memory and get written out as anchor + alias on serialisation).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With