Ruby on rails 如何在Jbuilder中合并JSON对象
我正在创建一个rails应用程序,具有主干/木偶前端。 我想获取下面的JSON对象并对其进行转换 这就是它现在的样子Ruby on rails 如何在Jbuilder中合并JSON对象,ruby-on-rails,json,jbuilder,Ruby On Rails,Json,Jbuilder,我正在创建一个rails应用程序,具有主干/木偶前端。 我想获取下面的JSON对象并对其进行转换 这就是它现在的样子 [{ "total_entries": 4 }, { "entries": [{ "user": { "id": 1, "fullname": "Paul Paulsen" },
[{
"total_entries": 4
},
{
"entries": [{
"user": {
"id": 1,
"fullname": "Paul Paulsen"
},
"reports": [{
"id": 1,
"name": "Anna Pearson",
"relation": "wife",
"phone": "2232",
"email": "adsas@sss.se"
}
]
},
{
"user": {
"id": 2,
"fullname": "Anna Palmgren"
},
"reports": [{
"id": 3,
"name": "Mika",
"relation": "Andersen",
"phone": "12312321",
"email": "aas@sss.se"
}]
}
]
}
]
我想让它看起来像这样
[{
"total_entries": 4
},
{
"entries": [{
"id": 1,
"fullname": "Paul Paulsen"
}, {
"id": 1,
"name": "Anna Pearson",
"relation": "wife",
"phone": "2232",
"email": "adsas@sss.se"
}, {
"id": 1,
"fullname": "Anna Palmgren"
}, {
"id": 3,
"name": "Mika",
"relation": "Andersen",
"phone": "12312321",
"email": "aas@sss.se"
}
]
}
]
这是我使用的Rabl文件/代码
json.array! [0,1] do |index|
if index == 0
json.total_entries @total
else
json.entries @reports.group_by(&:user) do |user, reports|
json.user user, :id, :fullname
json.reports reports do |report|
json.extract! report, :id, :name, :relation, :phone, :email
end
end
end
end
试试这个ruby代码片段
x= [{
"total_entries": 4
},
{
"entries": [{
"user": {
"id": 1,
"fullname": "Paul Paulsen"
},
"reports": [{
"id": 1,
"name": "Anna Pearson",
"relation": "wife",
"phone": "2232",
"email": "adsas@sss.se"
}
]
},
{
"user": {
"id": 2,
"fullname": "Anna Palmgren"
},
"reports": [{
"id": 3,
"name": "Mika",
"relation": "Andersen",
"phone": "12312321",
"email": "aas@sss.se"
}]
}
]
}
]
x[1][:entries] = x[1][:entries].map{|p| [p[:user], p[:reports]]}.flatten
这不是语法。你在展示,他们是不同的。对不起,你是对的。我现在已经编辑了。您需要尝试
ActiveRecord::Base.include\u root\u in\u json=false
以省略根对象ffom响应。别忘了重新启动服务器。