Removing empty values from an deeply nested Ruby hash

592 Views Asked by At

I'm building a healthcare application which supports some FHIR operations and therefore uses jsonb to store record in the database.

Now I want to remove empty values from my params hash. The JSON representation of the hash looks something like this:

{
  "id": "f134638f-b64b-4663-8295-9ebbd00a5044",
  "name": [
    {
      "text": "Dr. Maximilian Rohleder-Kirsch",
      "given": [
        "Maximilian"
      ],
      "family": "Rohleder-Kirsch",
      "prefix": [
        "Dr."
      ],
      "suffix": [
        ""
      ]
    }
  ],
  "active": true,
  "gender": "male",
  "address": [
    {
      "use": "home",
      "line": [
        "Wilhelmstraße"
      ],
      "type": "physical",
      "district": "Aßlar",
      "postalCode": "35614"
    }
  ],
  "birthDate": null,
  "identifier": [
    "#<AttrJson::Type::Model:0x00007f61a4059170>"
  ],
  "resourceType": "Patient",
  "deceasedBoolean": false,
  "deceasedDateTime": null
}

Removing empty key / value pairs from a normal, unnested hash is quite easy to do with the reject funtionality of Rails. The problem is (cause of the FHIR standard) that for example the suffix field contains another array, which is not blank by definition as it holds an empty string - but if that's the case, the whole suffix key should be deleted from the hash.

Any idea on how that could be done?

My plan was to recursively iterate over the keys and values with each and check if the value is an array.

1

There are 1 best solutions below

2
On BEST ANSWER

Try the below with recusrion:

def remove_blank(hash)
  hash.each do |_, value|
    if value.is_a? Hash
      remove_blank(value)
    elsif value.is_a?(Array) && value[0].is_a?(Hash)
      remove_blank(value[0])
    end
  end.reject! {|_, value| value.nil? || (value.is_a?(Array) && value.reject(&:empty?).empty?) }
end