Can I anchor individual items in a YAML collection? -


how can write books collection can anchor individual item? document invalid.

books:   - title: cat in hat &catinthehat     author: dr. seuss   - title: harry potter     author: jk rowling people:   - name: bill     favoritebook: *catinthehat   - name: edna 

yes can, in example don't have anchor, , since have alias without corresponding anchor, error (and should because not allowed).
have, scalar string the cat in hat &catinthehat has ampersand somewhere in middle.
if want define anchor need put before actual item (scalar, sequence, mapping).

if want alias scalar string the cat in hat (which value title) favoritebook can do:

title: &catinthehat cat in hat  author: dr. seuss 

with that, if after parsing access value favoritebook first element of sequence value toplevel key people (in python: data['people'][0]['favoritebook']) string "the cat in hat".

if want first element of sequence values books have do:

books:   - &catinthehat      title: cat in hat      author: dr. seuss   - title: harry potter     author: jk rowling 

then representation of mapping (dict/hash/map depending on programming language) directly can retrieve both title , author. depending on programming language , yaml parsers use, parser might "resolve" alias if refers scalar (string, integer etc) or not. dumping data represented yaml source, results in losing anchor , alias. collections (sequences, mappings), more not case (i.e. refer same collection object in memory , written out anchor + alias on serialisation).


Comments