I've got a JSON string that I need to remove all the blank values from. Something like:
[{"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"}]}]
I've considered going through all the elements and testing if they're "", and I've also considered loading the JSON through JSON.load and having the proc option remove blanks (though I'm fairly new to Ruby and don't know how to do that).
What is the best way to recursively remove all blank values from a JSON string? (Note that in this example variants is only one level deep for simplification. In reality it can be many levels deep.)
For completeness, the end result should look like:
[{"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"}]}]
(null values are OK in my case).
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
Result:
[{"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"}]}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With