huynhthinh
huynhthinh

Reputation: 37

Ruby on Rails loads yml file to special JSON

I have a requirements which read yml file into hash My code is below:

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

i can not get result sucessfully. my input file is

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

my expected result is a json object as

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

thanks

Upvotes: 1

Views: 1209

Answers (1)

shivam
shivam

Reputation: 16506

You are looking for to_json. Try this:

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

If you want to pretty print the result do this:

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

Upvotes: 2

Related Questions