在Ruby中,以递归方式从json字符串中删除空白项

时间:2015-05-24 19:42:51

标签: ruby-on-rails ruby json recursion is-empty

我有一个JSON字符串,我需要从中删除所有空白值。类似的东西:

[{"body":"","user":"mike","id":1234567,"type":"","published_at":"2015-05-22T14:51:00-04:00","title":null,"updated_at":"2015-05-23T22:04:38-04:00","postoffice":"Testing","tags":"","variants":[{"value":"", "service":"canada post"}]}]

我已经考虑过了所有的元素并测试了他们是否已经""并且我还考虑过通过JSON.load加载JSON并拥有proc选项删除空格(虽然我对Ruby很新,但不知道如何做到这一点)。

以递归方式从JSON字符串中删除所有空值的最佳方法是什么? (请注意,在这个示例中,变体只有一个级别以便简化。实际上它可以有很多级别。)

为完整起见,最终结果如下:

[{"user":"mike","id":1234567,"published_at":"2015-05-22T14:51:00-04:00","title":null,"updated_at":"2015-05-23T22:04:38-04:00","postoffice":"Testing","variants":[{"service":"canada post"}]}]

(在我的情况下,空值正常)。

3 个答案:

答案 0 :(得分:1)

require 'json'

json = JSON.parse(your_json)
json.first.reject! do |key, value|
  value == ''
end
puts json.to_s

答案 1 :(得分:1)

require 'json'

JSON.load(json, proc do |a|
  a.is_a?(Hash) && a.delete_if do |_k,v|
    next unless v.is_a?(String)
    v.empty?
  end
end

结果:

[{"user"=>"mike",
  "id"=>1234567,
  "published_at"=>"2015-05-22T14:51:00-04:00",
  "title"=>nil,
  "updated_at"=>"2015-05-23T22:04:38-04:00",
  "postoffice"=>"Testing",
  "variants"=>[{"service"=>"canada post"}]}]

答案 2 :(得分:0)

Note I had to change null to nil so it would be a valid ruby hash. The result is a bit verbose but gets the job done:

def strip_empties(json)
  json.each_with_object([]) do |record, results|
    record.each do |key, value|
      if value.is_a? Array
        results << { key => strip_empties(value) }
      else
        results << { key => value } unless value == ""
      end
    end
  end
end

result = strip_empties(json)

Output with nil but no empty strings:

=> [{:user=>"mike"},
 {:id=>1234567},
 {:published_at=>"2015-05-22T14:51:00-04:00"},
 {:title=>nil},
 {:updated_at=>"2015-05-23T22:04:38-04:00"},
 {:postoffice=>"Testing"},
 {:variants=>[{:service=>"canada post"}]}]