Ruby on rails 如何递归地将YAML文件展平为JSON对象,其中键是点分隔的字符串?

Ruby on rails 如何递归地将YAML文件展平为JSON对象,其中键是点分隔的字符串?,ruby-on-rails,ruby,rails-i18n,Ruby On Rails,Ruby,Rails I18n,例如,如果我有YAML文件 en: questions: new: 'New Question' other: recent: 'Recent' old: 'Old' 这将最终成为一个json对象,如 { 'questions.new': 'New Question', 'questions.other.recent': 'Recent', 'questions.other.old': 'Old' } @Ryan的递归答案是正确的,我只

例如,如果我有YAML文件

en:
  questions:
    new: 'New Question'
    other:
      recent: 'Recent'
      old: 'Old'
这将最终成为一个json对象,如

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

@Ryan的递归答案是正确的,我只是让它更红了一点:

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"}

然后,要将其转换为json格式,您只需要要求使用“json”并在哈希上调用to_json方法。

因为问题是关于在Rails应用程序上为i18n使用YAML文件,值得注意的是,gem提供了一个帮助器模块,可以完全像这样展开翻译:

test.rb

require 'yaml'
require 'json'
require 'i18n'

yaml = YAML.load <<YML
en:
  questions:
    new: 'New Question'
    other:
      recent: 'Recent'
      old: 'Old'
YML
include I18n::Backend::Flatten
puts JSON.pretty_generate flatten_translations(nil, yaml, nil, false)

答案是“不容易”。为什么要使用此哈希?我正在Rails应用程序上使用i18n的YAML文件。但我也在使用Polyglot在JavaScript中实现i18n,这需要JSON。
require 'yaml'
require 'json'
require 'i18n'

yaml = YAML.load <<YML
en:
  questions:
    new: 'New Question'
    other:
      recent: 'Recent'
      old: 'Old'
YML
include I18n::Backend::Flatten
puts JSON.pretty_generate flatten_translations(nil, yaml, nil, false)
$ ruby test.rb
{
  "en.questions.new": "New Question",
  "en.questions.other.recent": "Recent",
  "en.questions.other.old": "Old"
}