Search code examples
ruby-on-railsjsonrubyopenstruct

How to convert recursive/nested OpenStruct Object to Hash


I have an OpenStruct object and needs to convert to JSON data.

Sample Hash (from RSPEC helper):

def test_order
 {
   "id": 505311428702,
   "email": "[email protected]",
   "closed_at": "",
   "discount_codes": {
      "id": 507328175,
      "text": "test"
   }
 }
end

I'm using, below function for recursive:

def to_recursive_ostruct(hash)
  OpenStruct.new(hash.each_with_object({}) do |(key, val), memo|
    memo[key] = val.is_a?(Hash) ? to_recursive_ostruct(val) : val
  end)
end

For ex to_recursive_ostruct(test_order), will return:

<OpenStruct id=505311428702, email="[email protected]", closed_at="", ...>

Once converted, using OpenStructObject.marshal_dump:

{
:id=>505311428702, :email=>"[email protected]", :closed_at=>"", 

discount_codes=>#<OpenStruct id=507328175, text= "test">}
}

OpenStructObject.marshal_dump gives me the right data in first level,

I want also the nested data to beconverted.

What I really need is like:

{:id=>505311428702, :email=>"[email protected]", :closed_at=>"", :discount_codes=>{:id=>507328175, :text=> "test"} }

Please help, thanks in advance.


Solution

  • Check out docs.

    You can use OpenStruct#marshal_dump:

    openstruct_object.marshal_dump
    

    OpenStruct#to_h will work, too:

    openstruct_object.to_h
    

    You can convert your object to hash and then hash to JSON:

    openstruct_object.to_h.to_json
    

    But it looks like what you want is a Hash object, not JSON object.