活动记录结果和转换后的 JSON

发布于 2024-10-25 10:03:22 字数 481 浏览 3 评论 0原文

我需要将活动记录 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

苄①跕圉湢 2024-11-01 10:03:22

覆盖模型中的 to_json 方法

# your_model.rb, implement an instance method to_json
def to_json(options = {})
  {
    'cols' => [{'id' => 'whateveryoulike'}],
    'rows' => [{'id' => 'whateveryoulike'}]
  }.to_json(options)
end

请记住,接受 options 作为此方法的参数并将其传递给哈希的 to_json (或任何其他 to_json 调用您在该方法内进行的调用)。否则,该方法在集合 JSON 序列化时可能无法按预期运行。当然,由于您没有提供有关您的模型是什么以及它如何映射到所需 JSON 响应的任何详细信息,因此您必须根据需要实现列和行的表示。

这也适用于 to_xml

Override the to_json method in your model

# your_model.rb, implement an instance method to_json
def to_json(options = {})
  {
    'cols' => [{'id' => 'whateveryoulike'}],
    'rows' => [{'id' => 'whateveryoulike'}]
  }.to_json(options)
end

Remember, it is important to accept options as parameter to this method and pass it on to to_json of the hash (or any other to_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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文