Ruby on rails Rails过滤器JSON对象在渲染?

Ruby on rails Rails过滤器JSON对象在渲染?,ruby-on-rails,json,parsing,filter,Ruby On Rails,Json,Parsing,Filter,我有一个JSON字符串,我使用: objJson = JSON.parse(jsonString) respond_to do |format| format.html { render :json => objJson.to_json(:include => [:ID, :Name]) } end 问题是to_json只在模型上起作用,所以它忽略了我的过滤器 这是我的JSON: { "count":29, "results": [ {"ID":55603610

我有一个JSON字符串,我使用:

objJson = JSON.parse(jsonString)

respond_to do |format|
  format.html { render :json => objJson.to_json(:include =>  [:ID, :Name]) }
end
问题是
to_json
只在模型上起作用,所以它忽略了我的过滤器

这是我的JSON:

{
 "count":29,
 "results":
 [
   {"ID":556036109,"Name":"Mojos", "Url":"https://mojos/id300751949","currency":"USD"},
   {"ID":556036110,"Name":"Asav", "Url":"https://asav/id300751949","currency":"USD"}
 ]
}
有没有办法在渲染时过滤JSON对象


更新: 我使用了以下代码:

问题是objJson['results']向散列返回了一个数组,而不是一个散列

因此,正确的做法是:

objJson = objJson['results'].each { |x| x.keep_if {|k, v| KEYS_TO_KEEP.include?(k)} }

您可以在Ruby哈希上使用以下方法之一:


嘿,我在问题中添加了我的JSON。如果我使用:
@KEYS\u TO\u KEEP=[“results”]
则您的解决方案有效,但我无法从结果数组中选择特定的键。你知道如何做到这一点吗?你说的“我不能从结果数组中选择特定的键”是什么意思?你能发布你想做什么的示例代码吗?很抱歉,我没有注意到你编辑了这个问题。。无论如何,仍然无法工作,我在控制台上尝试了objJson['results'].include?('ID')只是为了测试,结果返回false。。尽管
objJson['results']
返回一个json数组。
objJson = objJson['results'].each { |x| x.keep_if {|k, v| KEYS_TO_KEEP.include?(k)} }
KEYS_TO_KEEP = ['ID', 'Name']
objJson['results'] =
  objJson['results'].keep_if {|k, v| KEYS_TO_KEEP.include?(k)}

format.html {render :json => objJson}