我可以将单个项目锚定在YAML集合中吗?

Joh*_*n W 4 yaml

如何编写Books集合以便我可以锚定单个项目?该文件无效.

Books:
  - Title: The Cat in the Hat &catInTheHat
    Author: Dr. Seuss
  - Title: Harry Potter
    Author: JK Rowling
People:
  - Name: Bill
    FavoriteBook: *catInTheHat
  - Name: Edna
Run Code Online (Sandbox Code Playgroud)

Ant*_*hon 8

是的,你可以,但在你的例子中你没有锚,并且因为你有一个没有相应锚的别名,你会得到一个错误(你应该因为这是不允许的).
你所拥有的是一个标量字符串The Cat in the Hat &catInTheHat,在中间某处有一个&符号.
如果要定义锚点,则需要将其放在实际项目之前(标量,序列,映射).

如果你只想为标量字符串The Cat in the Hat(这是标题的值)的别名,FavoriteBook你可以这样做:

Title: &catInTheHat The Cat in the Hat 
Author: Dr. Seuss
Run Code Online (Sandbox Code Playgroud)

有了这个,如果在解析之后你FavoriteBook从序列的第一个元素访问值,那就是toplevel键的值People(在Python中 data['People'][0]['FavoriteBook']),你会得到字符串"The Hat in the Hat".

如果您希望序列的第一个元素是Books您必须执行的值:

Books:
  - &catInTheHat 
    Title: The Cat in the Hat 
    Author: Dr. Seuss
  - Title: Harry Potter
    Author: JK Rowling
Run Code Online (Sandbox Code Playgroud)

然后你实际上得到了映射(dict/hash/map取决于你的编程语言)的表示,然后你可以从中直接检索标题和作者.根据您使用的编程语言和YAML解析器,解析器可能会"解析"别名(如果它引用标量(字符串,整数等)).转储从YAML源表示的数据会导致丢失锚点和别名.对于集合(序列,映射),通常情况并非如此(即它们在内存中引用相同的集合对象,并在序列化时写为锚点+别名).