【问题标题】:How to dump strings in YAML using literal scalar style?如何使用文字标量样式在 YAML 中转储字符串?
【发布时间】:2012-03-27 06:30:21
【问题描述】:

我有一大串格式化数据(例如 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 中的文字样式输出的工作方式。

【问题讨论】:

标签: ruby string yaml psych


【解决方案1】:
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 文档的其余部分。受您的代码启发,我用自己的方式更新了上面的问题,消除了您走树的步骤。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-25
  • 2019-07-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多