加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何将YAML文件递归展平为JSON对象,其中键是以

发布时间:2020-12-17 04:06:16 所属栏目:百科 来源:网络整理
导读:例如,如果我有YAML文件 en: questions: new: 'New Question' other: recent: 'Recent' old: 'Old' 这最终会像json对象一样 { 'questions.new': 'New Question','questions.other.recent': 'Recent','questions.other.old': 'Old'} 解决方法 由于问题是关于在
例如,如果我有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"
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读