ruby – 如何使用文字标量样式在YAML中转储字符串?
发布时间:2020-12-17 03:35:41 所属栏目:百科 来源:网络整理
导读:我有一大串格式化数据(例如 JSON),我希望在保留格式的同时使用Psych in ruby??转储到YAML. 基本上,我希望JSON使用literal style出现在YAML中: ---json: | { "page": 1,"results": [ "item","another" ],"total_pages": 0 } 但是,当我使用YAML.dump时,它不使
我有一大串格式化数据(例如
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": 0n}n" 我怎么能告诉Psych将scalars转换为想要的风格? 解: 非常感谢Aaron Patterson提出的我正在扩展的解决方案:https://gist.github.com/2023978 虽然有点冗长,但这个要点是一种标记ruby中某些字符串的工作方式,使用YAML中的文字样式输出. 解决方法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 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |