如何使用文字标量样式在 YAML 中转储字符串? [英] How to dump strings in YAML using literal scalar style?
问题描述
我有一大串格式化数据(例如 JSON),我想在 ruby 中使用 Psych 转储到 YAML同时保留格式.
I have a big string of formatted data (e.g. JSON) that I want to dump to YAML using Psych in ruby while preserving formatting.
基本上,我希望 JSON 使用 文字样式:
Basically, I want for JSON to appear in YAML using literal style:
---
json: |
{
"page": 1,
"results": [
"item", "another"
],
"total_pages": 0
}
但是,当我使用 YAML.dump
时,它不使用文字样式.我得到这样的东西:
However, when I use YAML.dump
it doesn't use literal style. I get something like this:
---
json: ! "{
"page": 1,
"results": [
"item", "another"
],
"total_pages":
0
}
"
我怎样才能告诉 Psych 以想要的样式转储标量?
How can I tell Psych to dump scalars in wanted style?
非常感谢 Aaron Patterson 的解决方案,我在此扩展:https://gist.github.com/2023978
Big thanks to Aaron Patterson for his solution that I'm expanding on here: https://gist.github.com/2023978
虽然有点冗长,但该要点是一种在 ruby 中标记某些字符串以使用 YAML 中的文字样式输出的工作方式.
Although a bit verbose, that gist is a working way of tagging certain strings in ruby to be output using literal style in YAML.
推荐答案
require 'psych'
# Construct an AST
visitor = Psych::Visitors::YAMLTree.new({})
visitor << DATA.read
ast = visitor.tree
# Find all scalars and modify their formatting
ast.grep(Psych::Nodes::Scalar).each do |node|
node.plain = false
node.quoted = true
node.style = Psych::Nodes::Scalar::LITERAL
end
begin
# Call the `yaml` method on the ast to convert to yaml
puts ast.yaml
rescue
# The `yaml` method was introduced in later versions, so fall back to
# constructing a visitor
Psych::Visitors::Emitter.new($stdout).accept ast
end
__END__
{
"page": 1,
"results": [
"item", "another"
],
"total_pages": 0
}
这篇关于如何使用文字标量样式在 YAML 中转储字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!