Ruby中如何生成带ActiveSupport::HashWithIndifferentAccess标识的YAML
问题原因
JSON.parse默认返回的是普通Ruby Hash类型,直接调用to_yaml生成的内容自然不会携带ActiveSupport::HashWithIndifferentAccess的类型标识。你需要将JSON解析结果的所有嵌套层级的Hash都统一转为HashWithIndifferentAccess类型,再生成YAML即可得到预期格式。
解决方案
首先安装activesupport依赖(如果是Rails环境可跳过这一步):
gem install activesupport
调整后的代码如下:
require 'yaml' require 'json' # 引入HashWithIndifferentAccess依赖 require 'active_support/core_ext/hash/indifferent_access' # 递归将所有嵌套Hash转为HashWithIndifferentAccess def recursive_turn_to_hwia(obj) case obj when Hash obj.each_with_object(HashWithIndifferentAccess.new) do |(key, value), result| result[key] = recursive_turn_to_hwia(value) end when Array obj.map { |item| recursive_turn_to_hwia(item) } else obj end end origin_json_str = '{"accepted":{"first_order_date":{"consition":"between_date","value":"2021-11-28 00:00:00&2021-11-22 00:00:00"}},"removed":{}}' parsed_hash = JSON.parse(origin_json_str) hwia_hash = recursive_turn_to_hwia(parsed_hash) puts hwia_hash.to_yaml
输出效果
运行上述代码得到的YAML输出如下:
--- !ruby/hash:ActiveSupport::HashWithIndifferentAccess accepted: !ruby/hash:ActiveSupport::HashWithIndifferentAccess first_order_date: !ruby/hash:ActiveSupport::HashWithIndifferentAccess consition: between_date value: 2021-11-28 00:00:00&2021-11-22 00:00:00 removed: !ruby/hash:ActiveSupport::HashWithIndifferentAccess {}
注:你给出的预期示例中key为
number_of_order属于示例笔误,实际输出会保留原JSON的first_order_date字段,类型标识完全符合你的预期。
内容的提问来源于stack exchange,提问作者HG Webs
相关产品推荐
相关产品推荐

