0

我有一个 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 对象?


更新:

我使用了 ssorallen代码:

KEYS_TO_KEEP = ['ID', 'Name']
objJson = JSON.parse(jsonString)

respond_to do |format|
  format.html {render :json => objJson['results'].keep_if {|k, v| KEYS_TO_KEEP.include?(k)}}
end

问题是 objJson['results'] 返回一个 Array 到 Hashes 而不是一个 Hash。

所以正确的做法是:

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

1 回答 1

0

您可以在 Ruby 哈希上使用其中一种方法,例如keep_if

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

format.html {render :json => objJson}
于 2012-12-26T18:25:28.017 回答