我在某种程度上得到了它,但我还没有看到一个没有提出比答案更多的问题的例子。
http://rhnh.net/2011/01/31/yaml-tutorial
# Set.new([1,2]).to_yaml
--- !ruby/object:Set
hash:
1: true
2: true
我知道我们正在声明一个 Set 标签。我不明白后续的哈希映射与它有什么关系。我们是在声明模式吗?有人可以给我看一个带有多个标签声明的例子吗?
我已经阅读了规范: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?拥有这些可以解决什么问题?
我似乎看到了很多“它们是什么”,而不是“它们为什么在那里”或“它们用于什么”。
最佳答案
我对 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 中获得
关于tags - 我不明白 YAML 标签是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15233335/