2

// 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"]
engineersmnky
  • 25,495
  • 2
  • 36
  • 52
Gautam
  • 84
  • 6

1 Answers1

5

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"]
Ketan Mangukiya
  • 360
  • 1
  • 7
  • Are you aware that Stack Overflow doesn't permit the utilization of solved answers from ChatGPT? – Rajagopalan Aug 12 '23 at 05:12
  • No..! I am here for finding and giving answers, doing R&D, helping Developers, getting help from other tools like ChatGPT and other AI tools. based on my R&D and knowledge, i used to provide the answer to the Questions, so it does not matter from where i got it and give. Thanks. – Ketan Mangukiya Aug 16 '23 at 05:01
  • If you have any better solution, please provide, so i can get some more knowledge from this problems and your solutions. Thanks. – Ketan Mangukiya Aug 16 '23 at 05:06
  • >>so it does not matter from where i got it and give<< https://meta.stackoverflow.com/questions/421831/temporary-policy-generative-ai-e-g-chatgpt-is-banned?cb=1 – Rajagopalan Aug 16 '23 at 08:15