I've got a yaml file document which have similar keys :-
line:
title: line-name
department: transcription
input_formats:
- input_format:
name: company
required: true
valid_type: general
- input_format:
name: website
required: false
valid_type: url
After generating new_file.yml the keys get sorted in alphabetical order :-
line:
department: transcription
input_formats:
-
input_format:
name: company
required: true
valid_type: general
-
input_format:
name: website
required: false
valid_type: url
title: line-name
the code for opening sample_file and making new_file is below :-
require 'yaml'
require 'ya2yaml'
@file = YAML::load(File.open("/Users/manish/Desktop/yaml/sample_file.yml"))
@new_file = File.new("/Users/manish/Desktop/yaml/new_file.yml", "w+")
@new_file.syswrite(@file.ya2yaml(:hash_order => ['title','department','input_formats']))
@new_file.syswrite(@file.ya2yaml(:hash_order => ['title','department','input_formats']))
, but it's not working. How can i retain the order?Finally i got the solution of the ordering issue.
The :hash_order only work for top level hash.
so it works only when i remove "line" key from my sample_file.yml. Then the order is preserved. :-
title: line-name
department: transcription
input_formats:
- input_format:
name: company
required: true
valid_type: general
- input_format:
name: website
required: false
valid_type: url
Can you change the format of the YAML file? Your YAML file specifies a hash with duplicate keys. That's a no-no.
If instead the YAML file used a list, like this:
line:
title: line-name
department: transcription
formats:
- input_format:
name: company
required: true
valid_type: general
- input_format:
name: website
required: false
valid_type: url
....
Those extra dashes would solve your problem for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With