YAML锚点先于别名规则影响可读性,相关工具是否有应对方案?
YAML锚点与别名的可读性问题及现有解决方案
YAML文档的可读性受限于**锚点(anchor)必须先于别名(alias)**的规则。以下是一段尝试描述应用商店三位用户信息的YAML代码及解析逻辑:
try { jsyaml.load(y.textContent); } catch (e) { console.error(e.message); }
<script src="https://unpkg.com/js-yaml@4.1.0/dist/js-yaml.min.js"></script> <script id="y" type="text/yaml"> jeff: &jeff FullName: Jeff Miller ParentalConsentRequired: false joe: FullName: Joe Miller ParentalConsentRequired: true Parents: - *jeff - *mary mary: &mary FullName: Mary Miller ParentalConsentRequired: false </script>
这段YAML是无效的,因为别名*mary出现在锚点&mary之前,而根据YAML规范,别名必须在锚点之后定义。
简单案例可以通过调整映射节点顺序(比如把mary:放在joe:之前)修复,但复杂场景下无法通过简单拓扑排序解决,最终生成的YAML会出现嵌套锚点,导致同类对象处于不同缩进层级,严重影响可读性,示例如下:
const obj = { jeff: { FullName: "Jeff Miller", ParentalConsentRequired: false }, joe: { FullName: "Joe Miller", ParentalConsentRequired: true }, mary: { FullName: "Mary Miller", ParentalConsentRequired: false } }; obj.joe.Parents = [obj.jeff, obj.mary]; y.textContent = jsyaml.dump(obj);
<script src="https://unpkg.com/js-yaml@4.1.0/dist/js-yaml.min.js"></script> <textarea rows="15" cols="80" id="y"></textarea>
针对这类可读性问题,现有YAML工具是否有对应的解决方案?(仅需技术领域整体情况说明,不接受工具推荐)
我提出两种核心解决思路:
- YAML生成器尽可能重排节点,使同类对象的锚点处于同一缩进层级(可能需要额外配置来定义对象类别);
- 解析器支持解析违反“锚点先于别名”规则的文档。
这两种方案是否已在现有工具中实现?
补充说明:讨论范围限定为无重复锚点的YAML文档。
内容的提问来源于stack exchange,提问作者Heiko Theißen
相关产品推荐
相关产品推荐

