如何递归地将 YAML 文件展平为 JSON 对象,其中键是点分隔的字符串? [英] How do I recursively flatten a YAML file into a JSON object where keys are dot separated strings?
本文介绍了如何递归地将 YAML 文件展平为 JSON 对象,其中键是点分隔的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,如果我有带有
en:
questions:
new: 'New Question'
other:
recent: 'Recent'
old: 'Old'
这最终会变成一个 json 对象
This would end up as a json object like
{
'questions.new': 'New Question',
'questions.other.recent': 'Recent',
'questions.other.old': 'Old'
}
推荐答案
由于问题是关于在 Rails 应用程序上使用 i18n 的 YAML 文件,值得注意的是 i18n
gem 提供了一个辅助模块 I18n::Backend::Flatten
完全像这样扁平化翻译:
Since the question is about using YAML files for i18n on a Rails app, it's worth noting that the i18n
gem provides a helper module I18n::Backend::Flatten
that flattens translations exactly like this:
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"
}
这篇关于如何递归地将 YAML 文件展平为 JSON 对象,其中键是点分隔的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文