问题描述
我有一个 OpenStruct
,它与许多其他 OpenStructs
嵌套在一起.将它们全部深度转换为 JSON 的最佳方法是什么?
I have an OpenStruct
that is nested with many other OpenStructs
. What's the best way to deeply convert them all to JSON?
理想情况下:
x = OpenStruct.new
x.y = OpenStruct.new
x.y.z = OpenStruct.new
z = 'hello'
x.to_json
// {y: z: 'hello'}
现实
{ <OpenStruct= ....> }
推荐答案
没有默认的方法来完成这样的任务,因为内置的 #to_hash
返回哈希表示,但它不会深度转换值.
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.
如果一个值是一个 OpenStruct
,它会原样返回并且不会被转换成一个 Hash
.
If a value is an OpenStruct
, it's returned as such and it's not converted into an Hash
.
然而,解决这个问题并不复杂.您可以创建一个遍历 OpenStruct
实例中的每个键/值的方法(例如使用 each_pair
),如果值为一个 OpenStruct
并返回一个 Ruby 基本类型的 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.
然后可以使用 .to_json
或 JSON.dump(hash)
轻松序列化此类 Hash
.
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}}
这篇关于将 OpenStruct 深度转换为 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!