活动记录结果和转换后的 JSON
我需要将活动记录 JSON 转换为如下所示:
{
cols: [{id: 'task', label: 'Task', type: 'string'},
{id: 'hours', label: 'Hours per Day', type: 'number'}],
rows: [{c:[{v: 'Work'}, {v: 11}]},
{c:[{v: 'Eat'}, {v: 2}]},
{c:[{v: 'Commute'}, {v: 2}]},
{c:[{v: 'Watch TV'}, {v:2}]},
{c:[{v: 'Sleep'}, {v:7, f:'7.000'}]}
]
}
这与从活动记录返回的 to_json 完全不同。转换 JSON 的最 Ruby 方式是什么?
I need to transform active record JSON to something like this:
{
cols: [{id: 'task', label: 'Task', type: 'string'},
{id: 'hours', label: 'Hours per Day', type: 'number'}],
rows: [{c:[{v: 'Work'}, {v: 11}]},
{c:[{v: 'Eat'}, {v: 2}]},
{c:[{v: 'Commute'}, {v: 2}]},
{c:[{v: 'Watch TV'}, {v:2}]},
{c:[{v: 'Sleep'}, {v:7, f:'7.000'}]}
]
}
That is totally different from what to_json returns from activerecord. What is the most ruby way to transform JSON?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
覆盖模型中的 to_json 方法
请记住,接受
options
作为此方法的参数并将其传递给哈希的to_json
(或任何其他to_json
调用您在该方法内进行的调用)。否则,该方法在集合 JSON 序列化时可能无法按预期运行。当然,由于您没有提供有关您的模型是什么以及它如何映射到所需 JSON 响应的任何详细信息,因此您必须根据需要实现列和行的表示。这也适用于
to_xml
。Override the to_json method in your model
Remember, it is important to accept
options
as parameter to this method and pass it on toto_json
of the hash (or any otherto_json
call you make inside this method, for that matter). Otherwise, the method may not behave as expected on collection JSON serialization. And of course since you haven't given any details as to what your model is and how it maps to the desired JSON response, you will have to implement the representation of cols and rows as you like.This also applies to
to_xml
.