Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force all nodes in yaml to be strings

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 yaml file. So how do I do this in a simple and smart way?

like image 277
Niels Kristian Avatar asked Feb 24 '23 03:02

Niels Kristian


2 Answers

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.

like image 180
kikito Avatar answered Feb 25 '23 18:02

kikito


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

like image 20
dexter Avatar answered Feb 25 '23 18:02

dexter