我有一大串格式化数据(例如
JSON),我希望在保留格式的同时使用Psych in ruby转储到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将scalars转换为想要的风格?
解:
非常感谢Aaron Patterson提出的我正在扩展的解决方案:https://gist.github.com/2023978
解决方法
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 }