如何在ruby中构建此JSON对象? [英] How do I build this JSON object in ruby?

查看:104
本文介绍了如何在ruby中构建此JSON对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在JSON中带来一组红宝石对象.我将需要通过id在JSON对象中找到该项目,因此我认为最好id是每个对象的键.这种结构对我来说最有意义:

I need to bring an array of ruby objects in JSON. I will need to find the item in the JSON object by id, so I think it is best that the id is the key of each object. This structure makes the most sense to me:

{
    "1":   {"attr1": "val1", "attr2": "val2"},
    "2":   {"attr1": "val1", "attr2": "val2"},
    "3":   {"attr1": "val1", "attr2": "val2"}
}

这样,我可以轻松地调用console.log(json_obj[id].attr1)

That way I can easily call into the json object like console.log(json_obj[id].attr1)

问题是我不太确定如何在ruby中构建它.据我所知:

The issue is that I am not quite sure how to build this in ruby. This is as far as I have gotten:

# in ruby
@book_types = []
BookType.all.each do |bt|
   @book_types << {bt.id => {:attr => bt.attr}}
end
@book_types = @book_types.to_json

// In JS
var bookTypes = JSON.parse('<%=raw @book_types %>');

2个问题:如何在红宝石中建造它?有没有更好的方法来完成我的工作?

2 questions: How can I build this in ruby? Is there a better way to accomplish what I am doing?

还请注意,我是在Rails框架上构建的

Also just a note that I am building this on the Rails framework

谢谢!

推荐答案

假设BookType是ActiveRecord类,则可以执行以下操作:

Assuming BookType is an ActiveRecord class, you can just do this:

BookType.all(:select => "attr1, attr2").to_json

...其中"attr1, attr2"是要包含在JSON中的属性的列表.

...where "attr1, attr2" is a list of the attributes you want to include in your JSON.

如果要将id作为键,则可以执行以下操作:

If you want the ids as keys, you can do this instead:

BookType.all.inject({}) { |hsh, bt|
  hsh[bt.id] = { "attr1" => bt.attr1, "attr2" => bt.attr2 }
  hsh
}.to_json

这篇关于如何在ruby中构建此JSON对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆