24

Why this (evaluated in Rails console)

[{:a => :b}].collect {|x| OpenStruct.new(x)}.to_json

adds a "table" record in there?

"[{\"table\":{\"a\":\"b\"}}]

I want just this:

"[{\"a\":\"b\"}]

Does it mean that Rails' to_json method handles OpenStruct in a different way? When I try it in the irb, it's not there:

require 'ostruct'
[{:a => :b}].collect {|x| OpenStruct.new(x)}.inspect

7 Answers 7

32

Because @table is a instance variable of OpenStruct and Object#as_json returns Hash of instance variables.

In my project, I implemented OpenStruct#as_json to override the behaviour.

require "ostruct"
class OpenStruct
  def as_json(options = nil)
    @table.as_json(options)
  end
end
3
  • I have been looking to over-ride the OpenStruct's inspect method all day now, and this is the only thing that has worked for me. Thanks.
    – yurisich
    Feb 4, 2013 at 22:15
  • Exactly what I need! You saved my day! Thx
    – phlegx
    Jan 30, 2018 at 10:41
  • This causes arguement errors for me. I have Failure and Success classes that inherit from OpenStruct. To be clear, I'm sure this works with OpenStruct, but with my other classes that inherit from it it breaks. Where I call new on to pass attributes for access from my services. It errors out where I dynamically pass attributes/values to the new method Jan 13, 2021 at 16:46
18

Use marshal_dump, although this somewhat defeats the purpose of converting it to an OpenStruct beforehand:

[{:a => :b}].collect {|x| OpenStruct.new(x).marshal_dump }.to_json
=> "[{\"a\":\"b\"}]"

The shorter way would be:

[{:a => :b}].to_json
"[{\"a\":\"b\"}]"

Alternatively you could moneky patch OpenStruct#as_json as shown in hiroshi's answer:

require "ostruct"
class OpenStruct
  def as_json(options = nil)
    @table.as_json(options)
  end
end
3
  • Yeah, the reason why I am doing that is I need to change the original hash structure (rename some fields, drop some others).
    – lzap
    Oct 20, 2011 at 11:26
  • 1
    Works like a charm. If there is any better way of doing that, let me know: gist.github.com/1300921
    – lzap
    Oct 20, 2011 at 11:28
  • Any downside to to_h.as_json(options) rather than referencing @table? It seems safer to use the public interface, even if I'm subclassing Ostruct.
    – Ramfjord
    Jul 7, 2018 at 18:58
14

I get around the problem by subclassing OpenStruct like so:

class DataStruct < OpenStruct
  def as_json(*args)
    super.as_json['table']
  end
end

then you can easily convert to JSON like so:

o = DataStruct.new(a:1, b:DataStruct.new(c:3))
o.to_json
# => "{\"a\":1,\"b\":{\"c\":3}}"

Neat huh? So in answer to your question, you'd write this instead:

[{:a => :b}].collect {|x| DataStruct.new(x)}.to_json

giving you:

=> "[{\"a\":\"b\"}]"

UPDATE FOR RUBY 2.7 (Feb 5, 2021)

require 'json'
require 'ostruct'

class OpenStruct
  def to_json
    to_hash.to_json
  end

  def to_hash
    to_h.map { |k, v|
      v.respond_to?(:to_hash) ? [k, v.to_hash] : [k, v]
    }.to_h
  end
end

o = OpenStruct.new(a:1, b:OpenStruct.new(c:3))
p o.to_json
2
  • 1
    Note I had to do super['table'] to get this to work. Jan 25, 2020 at 1:28
  • What makes this 'for Ruby 2.7' exactly?
    – Frexuz
    Jan 15, 2022 at 17:25
6

I found the other responses to be a tad confusing having landed here to just figure out how to turn my OpenStruct into a Hash or JSON. To clarify, you can just call marshal_dump on your OpenStruct.

$ OpenStruct.new(hello: :world).to_json
=> "{\"table\":{\"hello\":\"world\"}}"

$ OpenStruct.new(hello: :world).marshal_dump
=> {:hello=>:world}

$ OpenStruct.new(hello: :world).marshal_dump.to_json
=> "{\"hello\":\"world\"}"

I personally would be hesitant to monkey-patch OpenStruct unless you're doing it on a subclass, as it may have unintended consequences.

1
  • 1
    This is a better answer! I like it Nov 24, 2020 at 15:17
4

With ruby 2.1.2 you can use the following to get JSON without the table root element:

[{:a => :b}].collect {|x| OpenStruct.new(x).to_h}.to_json
 => "[{\"a\":\"b\"}]"
3
openstruct_array.map(&:to_h).as_json
1

The issue here is that internally it's doing a as_json which creates a Hash with the table key (because as_json serializes all of the instance variables of the object too and @table is an instance var of OpenStruct) and then it's doing a to_json on that which stringifies it.

So, the easiest way is to first just use to_h (which doesn't serialize the instance variables) and then to_json on that. So:

OpenStruct.new(x).to_h.json or in your case open_struct_array.map(&:to_h).to_json

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.