无需别名的 Ruby YAML 编写
我正在从 ruby 将数据写入 yaml 文件,并且经常在该文件上添加别名。例如:
- &id001
somekey: somevalue
- *id001
在我的例子中,我使用 yaml 文件来提高可读性,并向文件中的值添加名称,因为现有数据只是没有键的 |
分隔值。如何防止使用别名写入 yaml 文件?
[编辑]
为了进一步说明,这里是数据类型和问题的示例。
原始数据如下所示:
Ham|2.00|1
Eggs|0.50|12
Milk|2.00|2
我编写了一个 ruby 脚本将其转换为 yaml,它还会查看 sql 文件以获取适当的名称。 yaml 文件如下所示:
---
- !omap
- name: Ham
- &id001
price: 2.00
- quantity: 1
- !omap
- name: Eggs
- price: 0.50
- quantity: 12
- !omap
- name: Milk
- *id001
- quantity: 1
这会导致大型数据集出现问题,因为别名可能彼此距离很远,并且难以读取。
I am writing data to yaml files from ruby and I frequently get aliases dotted about the file. Things like:
- &id001
somekey: somevalue
- *id001
In my case I am using the yaml files to aid readability and add names to values in the files as the existing data is just |
separated values with no keys. How can I prevent the yaml files being written with aliases?
[Edit]
For further clarification here is an example of the type of data and problem.
The original data looks like:
Ham|2.00|1
Eggs|0.50|12
Milk|2.00|2
And I have written a ruby script to convert it to yaml, which also looks at an sql file to get the appropriate names. The yaml file looks like:
---
- !omap
- name: Ham
- &id001
price: 2.00
- quantity: 1
- !omap
- name: Eggs
- price: 0.50
- quantity: 12
- !omap
- name: Milk
- *id001
- quantity: 1
This causes a problem in large data sets because the aliases may be nowhere near each other and it makes it hard to read.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为什么使用 YAML::Omap?
一个更简单、更干净的解决方案是首先将数据读入哈希数组,如下所示:
然后执行:
结果是:
这对你有用吗?
Why are you using YAML::Omap's?
A much simpler and cleaner solution would be to first read the data into an array of hashes, as such:
and then just do:
resulting in:
Would that work for you?
发生这种情况是因为您在同一文档中多次输出同一对象。如果您不需要别名,则需要
复制
对象。比较以下内容:输出:
This happens because you are outputting the same object multiple times in the same document. If you do not want aliases, you need to
dup
the objects. Compare the following:Output:
当 YAML 太大并且具有嵌套结构时,复制每个对象以扩展别名可能会很复杂。
我使用的一种简单(hacky)方法是将 yaml 转换为 json。然后将其转换回 YAML。新的 YAML 不包含别名/锚点。
对于这个问题同样的答案:
如何在 Ruby 扩展别名中发出 YAML
It can be complicated to dup every object to expand aliases when YAML is too big and have nested structures.
One simple (hacky) approach I used was convert the yaml to json. and then convert it back to YAML. new YAML does not contain aliases/anchors.
Same answer on this question:
How to emit YAML in Ruby expanding aliases