首页 > 解决方案 > 如何使用 jbuilder 创建此自定义 JSON 布局

问题描述

我正在尝试使用 jbuilder 创建这个 JSON 布局:

   "entities" : {
       "users": {
         1: {name: 'abs', age: 44},
         2: {name: 'arms', age: 12},
         3: {name: 'legs', age: 34},
        }
    }

到目前为止我有这个:

json.entities do
  json.users @response.users do |user|
    json.(user, :id)
  end
end

但这又回来了:

entities: {
 users: [
  {
    id: 1
   }
  ]
}

我需要将“users”中的键设为 user.id 值,然后列出属性。

标签: ruby-on-railsjson

解决方案


这将为您提供所需的哈希值。.to_json如果需要字符串,则必须调用它。

hash = {users:{}}
@response.users.pluck(:id, :name, :age).each {|u| hash[:users][u[0]] = {name: u[1], age: u[2]}]}
# hash.to_json

推荐阅读