Pregunta

Tengo una gran cadena de datos formateados (p. ej.JSON) que quiero volcar a YAML usando Psych en Ruby conservando el formato.

Básicamente, quiero que JSON aparezca en YAML usando estilo literal:

---
json: |
  {
    "page": 1,
    "results": [
      "item", "another"
    ],
    "total_pages": 0
  }

Sin embargo, cuando uso YAML.dump no usa estilo literal.Me sale algo como esto:

---
json: ! "{\n  \"page\": 1,\n  \"results\": [\n    \"item\", \"another\"\n  ],\n  \"total_pages\":
  0\n}\n"

¿Cómo puedo decirle a Psych que descargue los escalares en el estilo deseado?


Solución:

Muchas gracias a Aaron Patterson por su solución que estoy ampliando aquí: https://gist.github.com/2023978

Aunque es un poco detallado, esa esencia es una forma funcional de etiquetar ciertas cadenas en Ruby para generarlas usando un estilo literal en YAML.

¿Fue útil?

Solución

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
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top