0

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.

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Max Kirsch
  • 441
  • 5
  • 24
  • Could you please define more precisely what you mean by "empty values"? For example, the value of the pair `suffix: ['']` is an array containing one element, which obviously is not empty. Also, when giving an example it's always helpful to show the desired result (as a Ruby object). – Cary Swoveland Dec 19 '20 at 19:04
  • I'll take your silence as a "no". – Cary Swoveland Dec 19 '20 at 23:32

1 Answers1

0

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
user11350468
  • 1,357
  • 1
  • 6
  • 22