如何使用文字标量样式在YAML中转储字符串?

mis*_*lav 5 ruby string yaml psych

我有我想要使用红宝石精极度紧张转储到YAML格式的数据(例如JSON)的大串,同时保留格式.

基本上,我希望JSON使用文字样式出现在YAML中:

---
json: |
  {
    "page": 1,
    "results": [
      "item", "another"
    ],
    "total_pages": 0
  }
Run Code Online (Sandbox Code Playgroud)

但是,当我使用YAML.dump它时不使用文字样式.我得到这样的东西:

---
json: ! "{\n  \"page\": 1,\n  \"results\": [\n    \"item\", \"another\"\n  ],\n  \"total_pages\":
  0\n}\n"
Run Code Online (Sandbox Code Playgroud)

我怎么能告诉Psych将scalars转换为想要的风格?


解:

非常感谢Aaron Patterson提出的我正在扩展的解决方案:https://gist.github.com/2023978

虽然有点冗长,但这个要点是一种标记ruby中某些字符串的工作方式,使用YAML中的文字样式输出.

小智 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
}
Run Code Online (Sandbox Code Playgroud)