【问题标题】:Rails filter JSON Object on render?Rails 在渲染时过滤 JSON 对象?
【发布时间】:2012-12-12 05:44:58
【问题描述】:

我有一个 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)} }

【问题讨论】:

    标签: ruby-on-rails json parsing filter


    【解决方案1】:

    您可以在 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}
    

    【讨论】:

    • 嘿,我在问题中添加了我的 JSON。如果我使用您的解决方案:@KEYS_TO_KEEP = ["results"],但我无法从结果数组中选择特定键。关于如何实现这一目标的任何想法?
    • “我不能从结果数组中选择特定的键”是什么意思?您可以发布您正在尝试做的示例代码吗?
    • 抱歉耽搁了我没有注意到你编辑了这个问题.. 无论如何仍然无法正常工作,我在控制台上尝试了 objJson['results'].include?('ID') 只是为了测试和它返回 false.. 虽然 objJson['results'] 返回一个 json 数组。
    猜你喜欢
    • 1970-01-01
    • 2014-07-10
    • 2011-03-28
    • 1970-01-01
    • 1970-01-01
    • 2017-04-20
    • 1970-01-01
    • 1970-01-01
    • 2015-11-28
    相关资源
    最近更新 更多