在YAML中,`<<`和`&`代表什么意思?

51

当我查看 cryptogen一个 fabric 命令)配置文件时,我发现了这个符号。

Profiles:

    SampleInsecureSolo:
        Orderer:
            <<: *OrdererDefaults  ## what is the `<<`
            Organizations:
                - *ExampleCom     ## what is the `*`
        Consortiums:
            SampleConsortium:
                Organizations:
                    - *Org1ExampleCom
                    - *Org2ExampleCom

在上面有两个符号<<*

Application: &ApplicationDefaults  # what is the `&` mean

    Organizations:

你可以看到还有一个符号&。 我不知道它们的含义。即使查看源代码(fabric/common/configtx/tool/configtxgen/main.go),我也没有得到任何信息。

2个回答

77

好的,那些都是YAML文件格式的元素,在这里用来提供一个configtxgen的配置文件。"&"符号表示锚点,"*"表示引用该锚点,基本上这是为了避免重复,例如:

person: &person
    name: "John Doe"

employee: &employee
    << : *person
    salary : 5000

将重复使用 person 字段并具有类似的含义,如下所示:

employee: &employee
    name   : "John Doe"
    salary : 5000

另一个例子是简单地复用值:

key1: &key some very common value

key2: *key

相当于:

key1: some very common value

key2: some very common value

由于abric/common/configtx/tool/configtxgen/main.go使用的是现成的YAML解析器,所以您在configtxgen相关代码中找不到任何对这些符号的引用。我建议您多了解一下YAML文件格式


5
在 https://yaml-online-parser.appspot.com/ 中尝试了你的 ': << *person' 代码行,但它无法编译。正确的代码应该是 '<< : *person'。并且需要将 << 缩进到下一行的 salary 上。 - Wappenull
3
@Wappenull:我可以确认你的修复并相应地更新了答案。 - lanoxx
快速问题,是否可以使用多个引用创建列表?例如,如果L1是-a -b -c,L2是-d -e -f,那么我是否可以使用l1a和l2a,分别将其锚定到L1和L2,来创建L3,即-a -b -c -d -e -f? - Dhiwakar Ravikumar
*&yaml spec 中有明确的描述。令人困惑的是 <<: 没有被说明清楚。 - spinkus

1

在 YAML 中,如果数据如下:

user: &userId '123'
username: *userId

equivalent yml is
user: '123'
username: '123'

or

equivalent json will is
{
    "user": "123",
    "username": "123"
}

这基本上允许重复使用数据,您也可以尝试使用数组而不是单个值,例如123

尝试使用任何yml转json在线转换器将下面的yml转换为json

users: &users
  k1: v1
  k2: v2
  
usernames: *users

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接