1

It seems to be pretty easy to create nested OpenStruct objects using JSON.parse:

JSON.parse( '{"a":{"b":0}}', object_class:OpenStruct )
#<OpenStruct a=#<OpenStruct b=0>>

Is there a simpler method of converting it back to json, without creating a recursive function (as demonstrated here: Deep Convert OpenStruct to JSON)?

Mike
  • 1,279
  • 7
  • 18

1 Answers1

0

Calling OpenStruct#to_json on your struct should do it:

[2] pry(main)> JSON.parse('{"a":{"b":0}}', object_class:OpenStruct).to_json
=> "{\"a\":{\"b\":0}}"

And from plain irb OpenStruct#to_json does not work:

irb(main):003:0> require 'ostruct'
=> true
irb(main):004:0> require 'json'
=> true
irb(main):005:0> JSON.parse('{"a":{"b":0}}', object_class:OpenStruct).to_json
=> "\"#<OpenStruct a=#<OpenStruct b=0>>\""

ruby 2.5.3, rails 4.2.11.1

Martin
  • 4,042
  • 2
  • 19
  • 29
  • 2
    Hi Martin, thank you for the response. That's a good suggestion and something I tried; however, the result I get is `"{\"table\":{\"a\":{\"table\":{\"b\":0},\"modifiable\":true}},\"modifiable\":true}"`. Perhaps I have done something wrong, but all I have seen to address that is to modify the `as_json` or `to_json`, since *table* is an instance of OpenStruct. This is my output of your example: `"{\"table\":{\"key1\":{\"table\":{\"key2\":1}}}}"` -- might you have already modified your version of to_json? – Mike Apr 03 '19 at 14:03
  • @Mike No I modified nothing. Please update your question because I dont really understand what `tables` have to do with `OpenStruct` and your current question as it is. Specify your input and desired output – Martin Apr 03 '19 at 14:08
  • I want to avoid complicating the question. This may be a rails-specific issue as I'm noticing different behavior between irb and rails console. Please refer here for an example https://stackoverflow.com/questions/7835047/collecting-hashes-into-openstruct-creates-table-entry/13777745 ; notice in the question asked, there's a *table* key when converting from OpenStruct. In my version I'm also seeing a *modifiable* key (as listed in my comment above) – Mike Apr 03 '19 at 14:37
  • @Mike What version of ruby and rails are you running? Im doing it in rails console and I see no `table` keys. Same for an example from https://stackoverflow.com/questions/7835047/collecting-hashes-into-openstruct-creates-table-entry/13777745 question. I have rails `4.2.11.1` and ruby `2.5.3` – Martin Apr 03 '19 at 14:43
  • ruby 2.5 / rails 5.1 (I used the rails-5 tag on the question, but it looks like I need to update the question for the ruby version) – Mike Apr 03 '19 at 15:00