Deep Convert OpenStruct to JSON
There is no default methods to accomplish such task because the built-in #to_hash
returns the Hash representation but it doesn't deep converts the values.
If a value is an OpenStruct
, it's returned as such and it's not converted into an Hash
.
However, this is not that complicated to solve. You can create a method that traverses each key/value in an OpenStruct
instance (e.g. using each_pair
), recursively descends into the nested OpenStruct
s if the value is an OpenStruct
and returns an Hash
of just Ruby basic types.
Such Hash
can then easily be serialized using either .to_json
or JSON.dump(hash)
.
This is a very quick example
def openstruct_to_hash(object, hash = {})
object.each_pair do |key, value|
hash[key] = value.is_a?(OpenStruct) ? openstruct_to_hash(value) : value
end
hash
end
openstruct_to_hash(OpenStruct.new(foo: 1, bar: OpenStruct.new(baz: 2)))
# => {:foo=>1, :bar=>{:baz=>2}}
Fixes to above solution to handle arrays
def open_struct_to_hash(object, hash = {})
object.each_pair do |key, value|
hash[key] = case value
when OpenStruct then open_struct_to_hash(value)
when Array then value.map { |v| open_struct_to_hash(v) }
else value
end
end
hash
end