本文介绍了将散列收集到 OpenStruct 中创建“表"入口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么会这样(在 Rails 控制台中评估)

Why this (evaluated in Rails console)

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

在那里添加一个表"记录?

adds a "table" record in there?

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

我只想要这个:

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

这是否意味着 Rails 的 to_json 方法以不同的方式处理 OpenStruct?当我在 irb 中尝试时,它不在那里:

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

推荐答案

使用 marshal_dump,尽管这有点违背了事先将其转换为 OpenStruct 的目的:

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

更短的方法是:

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

或者,您可以像 hiroshi 的回答中所示,对 OpenStruct#as_json 打补丁:

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

这篇关于将散列收集到 OpenStruct 中创建“表"入口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 04:24