Collecting hashes into OpenStruct creates "table" entry
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
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