koonse koonse - 2 months ago 41
Ruby Question

How do I recursively flatten a YAML file into a JSON object where keys are dot separated strings?

For example if I have YAML file with

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


This would end up as a json object like

{
'questions.new': 'New Question',
'questions.other.recent': 'Recent',
'questions.other.old': 'Old'
}

Answer
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
Comments