rubyflattenruby-hash

Ruby Flattening JSON Objects or Hash in


// Flattening JSON Objects // (want to merge all keys as a string from nested hash and want out put in array list)

input1 = {a: {b: {c: {} }, d:[] }, e: "e", f: nil, g: -2}
input2 = {a: {b: {c: {h: {j: ''}, m: {n: ''}}}, d: {k: {l: '' } }},e: "e",f: nil,g: -2}

// expected output for above input, should be an array with all these keys in any order

output1 = ["g", "f", "e", "a.b.c", "a.d"]
output2 = ["a.b.c.h.j", "a.b.c.m.n", "a.d.k.l", "e", "f", "g"]

Solution

  • Create one method

    def flatten_hash_keys(hash, prefix = nil)
      flat_keys = []
    
      hash.each do |key, value|
        current_key = prefix ? "#{prefix}.#{key}" : key.to_s
    
        if value.is_a?(Hash) && !value.empty?
          flat_keys.concat(flatten_hash_keys(value, current_key))
        else
          flat_keys << current_key
        end
      end
    
      flat_keys
    end
    

    This code defines a flatten_hash_keys method that takes a hash and an optional prefix. It recursively traverses the hash, appending keys to the flat_keys array. If a value is a non-empty hash, the method is called recursively with the new prefix. Otherwise, the current key is added to the array

    input1 = {a: {b: {c: {} }, d:[] }, e: "e", f: nil, g: -2}
    input2 = {a: {b: {c: {h: {j: ''}, m: {n: ''}}}, d: {k: {l: '' } }},e: "e",f: nil,g: -2}
    
    output1 = flatten_hash_keys(input1) #["a.b.c", "a.d", "e", "f", "g"]
    output2 = flatten_hash_keys(input2) #["a.b.c.h.j", "a.b.c.m.n", "a.d.k.l", "e", "f", "g"]