【问题标题】:YAML 1.2 anchors not working in js-yaml 3.10.0?YAML 1.2 锚在 js-yaml 3.10.0 中不起作用?
【发布时间】:2018-01-09 14:35:26
【问题描述】:

使用js-yaml 3.10.0 包在node.js (v4.8.7) 中加载YAML anchors 时(有一个很好的使用示例here)我收到以下错误:

“无法合并映射;提供的源对象不可接受”

例如,在我的输入 yaml 文件中,我的锚点如下所示:

defaultEd: &defaultEd
  - 'Pennsylvania College of Technology AS'
  - 'Pennsylvania College of Technology BS'

在我的输入 yaml 文件中引用锚点的地方有以下内容:

...
education:
  <<: *defaultEd
qs:
  - 'Reading'
  - 'Writing'
...

我希望在我的输出中完成以下内容:

education:
  - 'Pennsylvania College of Technology AS'
  - 'Pennsylvania College of Technology BS'

错误显示如下:

{ [YAMLException: cannot merge mappings; the provided source object is unacceptable at line 21, column 1:
    qs:
    ^]
  name: 'YAMLException',
  reason: 'cannot merge mappings; the provided source object is unacceptable',
  mark: 
   Mark {
     name: null,
     buffer: 'defaultEd: &defaultEd\n  - \'Pennsylvania College of Technology AS\'\n  - \'Pennsylvania College of Technology BS..
 <<: *defaultEd\nqs:\n  - \'Reading\'\n  - \'Writing\'\n  - \'Rithmatick\'\nexperience:\n  - {posName: \'Database Analyst / Net Tech\', companyName: \'Choices People Supporting People\'}\n\u0000',
     position: 435,
     line: 20,
     column: 0 },
  message: 'cannot merge mappings; the provided source object is unacceptable at line 21, column 1:\n    qs:\n    ^' }
Error View file does not exist: someTest.yml

【问题讨论】:

  • 在这种情况下,不需要合并映射。你可以使用education: *defaultEd。我猜 js-yaml 禁止在没有什么要合并的时候进行合并。
  • 实际上,我刚刚看到,锚点defaultEd 不是映射。所以没有办法合并它。您能否指定您希望在education 中包含哪些类型的数据?可能我使用education: *defaultEd 的建议仍然是正确的。
  • @tinita 是的,做到了,谢谢。我不知道映射是什么,但我猜映射与它是某种分层对象有关?
  • @tinita 你可以添加一个答案,我会选择它作为正确的。

标签: javascript node.js yaml


【解决方案1】:

您可能误解/混淆了别名的用法和合并键&lt;&lt;

YAML 中的任何节点都可以附加锚点:

---
mapping: &map
  a: 1
  b: 2
sequence: &seq
  - a
  - b
scalar: &scalar foo
mapping-alias: *map
sequence-alias: *seq
scalar-alias: *scalar

某些处理器支持合并键 &lt;&lt;,它不是 YAML 规范本身的一部分。它允许您将别名映射合并到另一个映射中。

defaults: &defaults
  a: 1
  b: 2
# .....
some-mapping:
  <<: *defaults
  c: 3

http://yaml.org/type/merge.html

YAML 中的映射在编程语言中通常称为字典、关联数组、哈希或有时称为对象 (Javascript)。

在你的情况下,你可能只想:

education: *defaultEd

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-16
    • 1970-01-01
    • 2020-07-18
    • 2021-07-02
    • 2021-07-03
    • 2015-11-23
    相关资源
    最近更新 更多