我有一大串格式化数据(例如JSON),我想在ruby 中使用Psych转储到YAML,同时保留格式。
基本上,我希望JSON使用literal style:
出现在YAML中---
json: |
{
"page": 1,
"results": [
"item", "another"
],
"total_pages": 0
}
但是,当我使用YAML.dump
时,它不使用文字样式。我得到这样的东西:
---
json: ! "{\n \"page\": 1,\n \"results\": [\n \"item\", \"another\"\n ],\n \"total_pages\":
0\n}\n"
我怎么能告诉Psych以想要的方式抛弃标量?
非常感谢Aaron Patterson提出的我正在扩展的解决方案:https://gist.github.com/2023978
虽然有点冗长,但这个要点是一种标记ruby中某些字符串的工作方式,使用YAML中的文字样式输出。
答案 0 :(得分:8)
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
}