Collecting hashes into OpenStruct creates “table” entry

前端 未结 6 888
滥情空心
滥情空心 2021-02-04 05:46

Why this (evaluated in Rails console)

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

adds a \"table\" record in there?



        
6条回答
  •  无人共我
    2021-02-04 06:13

    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
    

提交回复
热议问题