简体   繁体   English

从深度嵌套的 Ruby hash 中删除空值

[英]Removing empty values from an deeply nested Ruby hash

I'm building a healthcare application which supports some FHIR operations and therefore uses jsonb to store record in the database.我正在构建一个支持某些 FHIR 操作的医疗保健应用程序,因此使用 jsonb 将记录存储在数据库中。

Now I want to remove empty values from my params hash.现在我想从参数 hash 中删除空值。 The JSON representation of the hash looks something like this: hash 的 JSON 表示形式如下所示:

{
  "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.使用 Rails 的reject功能很容易从正常的、未嵌套的 hash 中删除空键/值对。 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.问题是(由于 FHIR 标准)例如, suffix字段包含另一个数组,根据定义,该数组不是空白的,因为它包含一个空字符串 - 但如果是这种情况,则应从 hash 中删除整个suffix键。

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.我的计划是对每个键和值进行递归迭代,并检查该值是否为数组。

Try the below with recusrion:尝试以下 recursion:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM