2013-03-05 67 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