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

例如,如果我有YAML文件

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

这最终会像json对象一样

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

解决方法

由于问题是关于在Rails应用程序上使用i18n的YAML文件,值得注意的是 i18n gem提供了一个帮助程序模块 I18n::Backend::Flatten,它完全像这样平移翻译:

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)

输出:

$ruby test.rb
{
  "en.questions.new": "New Question","en.questions.other.recent": "Recent","en.questions.other.old": "Old"
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐