开发者

How to force all nodes in yaml to be strings

开发者 https://www.devze.com 2023-04-01 14:42 出处:网络
I have a huge config yaml file, where all of the nodes should be read as strings. An example: model_names:

I have a huge config yaml file, where all of the nodes should be read as strings. An example:

model_names:
  Audi:
    A4:
      - A4
      - A 4
  Fiat:
    500:
      - 500  

I load out the file in rails:

catalogue = File.read("#{Rails.root}/config/cars_catalogue.yml")
CARS_CATALOGUE = YAML.load(catalogue)

My problem is, that if I ask for:

CARS_CATALOGUE['model_names']['Fiat']['500']

It returns nil, because it thinks that 500: is a fixnum - but all of the nodes should ALWAYS be strings - and i don't want to enforce this with quotes everywhere in the y开发者_如何学JAVAaml file. So how do I do this in a simple and smart way?


Can you regenerate the file? If yes, then simply add quotes to the numbers:

model_names:
  Audi:
    A4:
      - A4
      - A 4
  Fiat:
    "500":
      - 500

That should do it.


stringify_keys should convert all keys to string

catalogue = File.read("#{Rails.root}/config/cars_catalogue.yml")
CARS_CATALOGUE = YAML.load(catalogue).stringify_keys

Still better to use YAML.load(catalogue).symbolize_keys to convert all keys to symbols


Rails currently has a recursive key stringificaiton function; check it

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号