2013-03-05 150 views
21

我在某种程度上了解它,但我还没有看到一个没有提出更多问题而不是答案的例子。我不明白什么是YAML标签

http://rhnh.net/2011/01/31/yaml-tutorial

# Set.new([1,2]).to_yaml 
--- !ruby/object:Set 
hash: 
    1: true 
    2: true 

我得到我们正在声明一套标签。我没有得到随后的哈希映射与它做什么。我们是否在声明一个模式?有人能给我看一个有多个标签声明的例子吗? http://yaml.org/spec/1.2/spec.html#id2761292

%TAG ! tag:clarkevans.com,2002: 

这是宣布一个模式:

我已经通过规范看?为了成功解析文件,解析器还需要做些什么吗?某种类型的模式文件?

http://www.yaml.org/refcard.html

Tag property: # Usually unspecified. 
    none : Unspecified tag (automatically resolved by application). 
    '!'  : Non-specific tag (by default, "!!map"/"!!seq"/"!!str"). 
    '!foo' : Primary (by convention, means a local "!foo" tag). 
    '!!foo' : Secondary (by convention, means "tag:yaml.org,2002:foo"). 
    '!h!foo': Requires "%TAG !h! <prefix>" (and then means "<prefix>foo"). 
    '!<foo>': Verbatim tag (always means "foo"). 

为什么相关的有原发性和继发性标签,以及为什么二级标签指的是URI?有这些问题正在解决什么问题?

我似乎看到了很多“他们是什么”,并且没有“他们为什么在那里”或“他们用了什么”。

+2

可以在你的第一个例子,'#设置。 new([1,2])。to_yaml'实际上是一个*注释* - 它是一个ruby语句,它会在它下面输出YAML。 – AlexFoxGill 2013-06-19 12:57:46

回答

13

我不知道了很多关于YAML,但我给它一个镜头:

标签是用来表示类型。正如您从那里的“refcard”中看到的那样,使用!来声明标签。 %TAG指令有点像声明标签的快捷方式。

我将用PyYaml演示。 PyYaml可以将!!python/object:的辅助标签解析为实际的python对象。双重感叹号本身是一种替代,简写为!tag:yaml.org,2002:,将整个表达式转换为!tag:yaml.org,2002:python/object:。这个说法有点笨重,我们要创建一个对象每次打字了,所以我们给它使用%TAG指令别名:

%TAG !py! tag:yaml.org,2002:python/object:   # declares the tag alias 
--- 
- !py!__main__.MyClass        # creates an instance of MyClass 

- !!python/object:__main__.MyClass     # equivalent with no alias 

- !<tag:yaml.org,2002:python/object:__main__.MyClass> # equivalent using primary tag 

节点由它们的默认类型解析,如果你没有标签注释。以下是等价的:

- 1: Alex 
- !!int "1": !!str "Alex" 

下面是使用PyYaml证明标签的使用一个完整的Python程序:

import yaml 

class Entity: 
    def __init__(self, idNum, components): 
     self.id = idNum 
     self.components = components 
    def __repr__(self): 
     return "%s(id=%r, components=%r)" % (
      self.__class__.__name__, self.id, self.components) 

class Component: 
    def __init__(self, name): 
     self.name = name 
    def __repr__(self): 
     return "%s(name=%r)" % (
      self.__class__.__name__, self.name) 

text = """ 
%TAG !py! tag:yaml.org,2002:python/object:__main__. 
--- 
- !py!Component &transform 
    name: Transform 

- !!python/object:__main__.Component &render 
    name: Render 

- !<tag:yaml.org,2002:python/object:__main__.Entity> 
    id: 123 
    components: [*transform, *render] 

- !<tag:yaml.org,2002:int> "3" 
""" 

result = yaml.load(text) 

更多信息可在spec