转储 YAML 时如何强制使用双引号? [英] How do I force double-quotes when dumping YAML?

查看:119
本文介绍了转储 YAML 时如何强制使用双引号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小脚本来自动化 YAML 文件中的一些事情.

I have a small script to automate some things in YAML files.

我阅读了原始的 YAML 文件并将其转换为哈希,然后 dump 修改后到文件中:

I read the original YAML file and convert it into a hash and then dump it to the file after modifying it:

File.open(output_file, "w") do |out|
  YAML.dump(modified_hash, out)
end

这很好用,但如果不需要,它会删除字符串周围的双引号.这是有效的 YAML,但看起来不太好.

That works fine, but it removes double-quotes around the string if they aren't needed. That's valid YAML, but it doesn't look very nice.

我可以在每个字符串的末尾添加一个空格来强制使用单引号,但我对此不太满意.有没有办法在字符串周围强制使用双引号?

I could add a space at the end of every string to force single-quotes, but I'm not too happy with that. Is there any way of forcing double-quotes around strings?

推荐答案

我找到了一个解决方案,虽然很奇怪,但有效.

I found a solution, it's weird, but it works.

为了强制单引号,我遍历了哈希并将"foobar"(注意空格)附加到每个值.使用YAML.dump后,我再次打开文件并将"foobar"替换为空字符串.

To force single quotes, I went through the hash and appended "foobar " (note the space) to every value. After using YAML.dump, I opened the file again and replaced "foobar " with empty string.

为了强制双引号,我发现附加 "foo \nbar" 可以完成这项工作.再次,我然后打开文件并将 "foo \\nbar" 替换为空字符串.奇怪,但有效.

To force double quotes, I found that appending "foo \nbar" does the job. Again, I then open the file and replace "foo \\nbar" with empty string. Weird, but works.

请注意,您可能希望选择比 foobar 更不可能使用的东西.

Note that you probably want to chose something less likely used than foobar.

这篇关于转储 YAML 时如何强制使用双引号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆