过滤json对象的数组

时间:2011-10-18 15:19:12

标签: ruby-on-rails ruby arrays json filter

我有以下json对象数组。

[{"template":{"title":"title 1"}},{"template":{"title":"title 1"}},{"template":{"title":"title1111"}},{"template":{"title":""}},{"template":{"title":""}},{"template":{"title":"this is the title"}},{"template":{"title":"title232"}},{"template":{"title":"title with msg"}},{"template":{"title":"title with msg"}},{"template":{"title":"title with msg"}},{"template":{"title":"title with msg"}},{"template":{"title":"title with msg"}},{"template":{"title":"title with msg"}},{"template":{"title":"title with msg"}},{"template":{"title":"title with msg"}},{"template":{"title":"title with msg"}},{"template":{"title":"title with msg"}},{"template":{"title":"title with msg"}},{"template":{"title":"this is a title"}},{"template":{"title":"this is a title"}},{"template":{"title":"this is a title"}},{"template":{"title":"some title"}},{"template":{"title":"some title"}},{"template":{"title":"some title"}},{"template":{"title":"some title"}}]

我希望这个数组像

[{'title': 'some title'}, {'title': 'some other title'}, ...]

所以基本上我不希望js响应中的模板属性。 我从下面的rails代码中得到了这个

@templates = Template.find_all_by_user_id(current_user.id, :select=>'title', :conditions=>"title is not null")

@templates.to_json是什么给了我这个json对象数组

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

检查:http://apidock.com/rails/ActiveRecord/Serialization/to_json

Template.include_root_in_json = false

答案 1 :(得分:0)

我认为在这种情况下,你可以只收集整个Template集合的属性:

@templates = Template.find_all_by_user_id(current_user.id, :select=>'title', :conditions=>"title is not null").collect(&:attributes)

(向右滚动可查看该行末尾添加的.collect(&:attributes)。)