Rails 请问怎么把 Hash 通过 jbuilder 变成 json

birbird · August 06, 2014 · Last by liukgg replied at December 02, 2016 · 2291 hits

我有一个 Hash,这个样子的

{
    "B" = > [ # < Position id : 4, name : "B1" > ,
              # < Position id : 7, name : "B2" > ],
    "C" = > [ # < Position id : 1, name : "C1" > ,
              # < Position id : 2, name : "C2" > ],
}

其中 Position 是我自己定义的类。 期望把他输出成这样的 json

{
    positions: {
        B : [
            { id : 4, name : "B1" },
            { id : 7, name : "B2" },
        ],
        C : [
            { id : 1, name : "C1" },
            { id : 2, name : "C2" },
        ],
    },
}

我是这么干的, json.set! :positions, @place.positions_ 但是不行,说 undefined method `key?' for #JSON::Ext::Generator::State:0x5a2f070

请问这个该怎么搞啊? 谢啦先!

自问自答一下,这样可以,不知道是不是最好的写法

json.positions do
  @place.positions_.each do |k, v| 
    json.set! k do
      json.array! v
    end
  end
end

更加简单的方式:

@hash = { a: 1, b: 2, c: 'test'}

json.(@hash, :a, :b, :c)

参考: https://github.com/rails/jbuilder

You need to Sign in before reply, if you don't have an account, please Sign up first.