Ruby on Rails将yml文件加载到特殊的JSON

时间:2015-03-28 07:50:46

标签: ruby-on-rails ruby

我有一个将yml文件读入哈希的要求 我的代码如下:

def self.load_key
    json_obj = {}
    hsh_keys = YAML.load_file(File.open('config/locales/en.yml'))
    convert(hsh_keys, json_obj)
    p json_obj 
  end

  def self.convert(h, json_obj)
    h.each do |k,v|
      value = v || k          
      if value.is_a?(Hash) || value.is_a?(Array)
        convert(value)
      else
        json_obj.merge!({k v})
      end
    end
    json_obj
  end

我无法获得成功的结果。 我的输入文件是

en:
  hello: "Hello %{user}!"
  en: English
  alerts:
    account:
      locked: "User account is locked."
      disabled: "User account is disabled."

我的预期结果是json对象

{
      "hello": "Hello %{user}!"
      "en": "English"
      "alerts.account.locked": "User account is locked."
      "alerts.account.disabled": "User account is disabled."
}

感谢

1 个答案:

答案 0 :(得分:2)

您正在寻找to_json。试试这个:

hsh_keys = YAML.load_file(File.open('config/locales/en.yml')).to_json
puts hsh_keys
# {hello: "Hello %{user}!", en: English, alerts.account.locked: "User account is locked.", alerts.account.disabled: "User account is disabled."}

如果你想打印结果,请执行以下操作:

puts JSON.pretty_generate(YAML.load_file(File.open('config/locales/en.yml')))
# {
#    hello: "Hello %{user}!"
#    en: English
#    alerts.account.locked: "User account is locked."
#    alerts.account.disabled: "User account is disabled."
# }