我有一个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']将一个数组返回给Hashes而不是一个Hash。
所以正确的做法是:
objJson = objJson['results'].each { |x| x.keep_if {|k, v| KEYS_TO_KEEP.include?(k)} }
答案 0 :(得分:0)
您可以在像keep_if
这样的Ruby哈希中使用其中一种方法:
KEYS_TO_KEEP = ['ID', 'Name']
objJson['results'] =
objJson['results'].keep_if {|k, v| KEYS_TO_KEEP.include?(k)}
format.html {render :json => objJson}