Come scaricare stringhe in YAML usando lo stile scalare letterale?
Domanda
Ho una grande stringa di dati formattati (ad esempio JSON) che voglio scaricare su YAML usando Psych in Ruby preservendo la formattazione .
Fondamentalmente, voglio che JSON appaia in YAML usando stile letterale :
.
---
json: |
{
"page": 1,
"results": [
"item", "another"
],
"total_pages": 0
}
Come posso dire a Psych da scaricare Scalari in stile ricercato?
.
Soluzione:
Grandi grazie ad Aaron Patterson per la sua soluzione che sto espandendo qui: https://gist.github.COM / 2023978
Sebbene un po 'verboso, quel gist è un modo di funzionamento per taggare determinate stringhe in rubino da emettere usando lo stile letterale in YAML.
Soluzione
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
}
. Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow