How did I recursively flatten the YAML file into a JSON object where the keys are separated by dots?

For example, if I have a YAML file with

en:
  questions:
    new: 'New Question'
    other:
      recent: 'Recent'
      old: 'Old'

This would end up as a json object, for example

{
  'questions.new': 'New Question',
  'questions.other.recent': 'Recent',
  'questions.other.old': 'Old'
}
+4
source share
2 answers
require 'yaml'

yml = %Q{
en:
  questions:
    new: 'New Question'
    other:
      recent: 'Recent'
      old: 'Old'
}

yml = YAML.load(yml)
translations = {}

def process_hash(translations, current_key, hash)
  hash.each do |new_key, value|
    combined_key = [current_key, new_key].delete_if { |k| k.blank? }.join('.')
    if value.is_a?(Hash)
      process_hash(translations, combined_key, value)
    else
      translations[combined_key] = value
    end
  end
end

process_hash(translations, '', yml['en'])
p translations
+9
source

@ Ryan's recursive answer is the way to go, I just made it a little more Rubyish:

yml = YAML.load(yml)['en']

def flatten_hash(my_hash, parent=[])
  my_hash.flat_map do |key, value|
    case value
      when Hash then flatten_hash( value, parent+[key] )
      else [(parent+[key]).join('.'), value]
    end
  end
end

p flatten_hash(yml) #=> ["questions.new", "New Question", "questions.other.recent", "Recent", "questions.other.old", "Old"]
p Hash[*flatten_hash(yml)] #=> {"questions.new"=>"New Question", "questions.other.recent"=>"Recent", "questions.other.old"=>"Old"}

Then, to get it in json format, you just need to require "json" and call the to_json method for the hash.

+5
source

All Articles