Search code examples
ruby-on-railsrubyjsonrecursionis-empty

In Ruby, recursively remove blank items from json string


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).


Solution

  • 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"}]}]