6

我有一大串格式化数据(例如 JSON),我想在 ruby​​ 中使用 Psych 转储到 YAML,同时保留格式

基本上,我希望 JSON 使用文字样式出现在 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 中的文字样式输出的工作方式。

4

1 回答 1

11
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
}
于 2012-03-12T16:20:59.673 回答