c++ - Yaml-cpp 解析不起作用冒号后缺少空格

标签 c++ parsing yaml yaml-cpp

我在 yaml-cpp 解析器中遇到了问题。当我尝试加载以下定义时:

DsUniversity:
  university_typ: {type: enum, values:[Fachhochschule, Universitat, Berufsakademie]}
  students_at_university: {type: string(50)}

我收到以下错误:

Error: yaml-cpp: error at line 2, column 39: end of map flow not found

我试图在 http://yaml-online-parser.appspot.com/ 上验证 yaml 有效性和 http://yamllint.com/并且两种服务都报告 yaml 有效。

问题是由“值:”定义后缺少空格引起的。当 yaml 更新为以下格式时:

DsUniversity:
  university_typ: {type: enum, values: [Fachhochschule, Universitat, Berufsakademie]}
  students_at_university: {type: string(50)}

一切正常。

有什么方法可以配置/更新/修复 yaml-cpp 解析器以继续处理冒号后缺少空格的 yaml?

添加: 看来问题是由要求将空字符作为分隔符引起的。当我将测试片段简化为

DsUniversity:[Fachhochschule, Universitat, Berufsakademie]

yaml-cpp 解析器将其读取为一个标量值“DsUniversity:[Fachhochschule, Universitat, Berufsakademie]”。当在冒号后添加空字符时,yaml-cpp 会正确加载带有序列的元素。

最佳答案

yaml-cpp 在这里是正确的,而那些在线验证器是不正确的。来自YAML 1.2 spec :

7.4.2. Flow Mappings

Normally, YAML insists the “:” mapping value indicator be separated from the value by white space. A benefit of this restriction is that the “:” character can be used inside plain scalars, as long as it is not followed by white space. This allows for unquoted URLs and timestamps. It is also a potential source for confusion as “a:1” is a plain scalar and not a key: value pair.

...

To ensure JSON compatibility, if a key inside a flow mapping is JSON-like, YAML allows the following value to be specified adjacent to the “:”. This causes no ambiguity, as all JSON-like keys are surrounded by indicators. However, as this greatly reduces readability, YAML processors should separate the value from the “:” on output, even in this case.

在您的示例中,您处于流映射(意思是被 {} 包围的 map )中,但您的 key 不是JSON-like:您只有一个普通标量(values 未加引号)。要类似于 JSON,键需要用单引号或双引号引起来,或者它可以是嵌套的流序列或映射本身。

在您的简化示例中,

DsUniversity:[Fachhochschule, Universitat, Berufsakademie]

yaml-cpp 和在线验证器都将其正确解析为单个标量 - 为了成为 map ,如您所愿,您需要在 : 之后留一个空格。

为什么 YAML 需要那个空间?

在简单的纯标量情况下:

a:b

可能是不明确的:它可以被读作标量 a:b 或映射 {a: b}。 YAML 选择将此作为标量读取,以便 URL 可以轻松嵌入 YAML 而无需引用:

http://stackoverflow.com

是一个标量(如您所料),而不是 map {http://stackoverflow.com}!

在流上下文中,有一种情况是没有歧义的:当引用键时,例如:

{"a":b}

这被称为类 JSON,因为它类似于 JSON,需要用引号将所有 标量括起来。在这种情况下,YAML 知道键在结束引号处结束,因此可以确保值立即开始。

这种行为是明确允许的,因为 JSON 本身允许这样的事情

{"a":"b"}

由于 YAML 1.2 是 JSON 的严格超集,因此这在 YAML 中必须是合法的。

关于c++ - Yaml-cpp 解析不起作用冒号后缺少空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25642783/

相关文章:

azure - 如何与 Kubernetes 上的 Secrets Store CSI 驱动程序共享所有 Azure KeyVault key 和 secret

c++ - 编译推力示例代码时找不到头文件

parsing - 如何在 REBOL 的 PARSE 中进行局部词赋值?

c - 用C语言从xml中解析一个字符?

python - 模块 'avro.schema' 没有属性 'parse'

java - 如何将测试数据作为从 YAML 文件读取的 Object[][] 进行管理?

c++ - 如何返回带参数的 lambda 函数?

c++ - While 循环的变量未被识别为已初始化

c++ - 带命令提示符的命名管道

azure-devops - 导航到 azure devops 构建服务器中的构建源目录