Collecting hashes into OpenStruct creates “table” entry

前端 未结 6 881
滥情空心
滥情空心 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-04 06:00

    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\"}]"
    

提交回复
热议问题