How to parse yaml in ruby without type mapping
Вопрос
I would like to get data from a Mysql dump in yaml (PHPMyAdmin), but data are not surrounded by quotation mark.
I have zipcode that can start by 0 and after parsing I get decimal version of octal value, in place of simple string.
How can I do to force Yaml parser not to do auto-mapping, or just get all data as they are string ?
Thanks
== UPDATE ==
2185:
id: 3274
civility: Mr
address: CROIX DES COMBES
zipcode: 04270
Решение
If your zipcode values are strings, which they probably should be in the database, and they are converted correctly to YAML, then they will be reconverted back into strings by Ruby's YAML parser:
require 'yaml'
zip = '01234'
If we treat it as a string, it converts correctly.
zip.to_yaml # => "--- \"01234\"\n"
YAML.load(zip.to_yaml) # => "01234"
If we treat it as an integer, it has its leading 0
dropped, which I'd expect.
zip.to_i.to_yaml # => "--- 1234\n"
YAML.load(zip.to_i.to_yaml) # => 1234
In your sample:
zipcode: 04270
zipcode
is a YAML integer. It should be enclosed inside quotes to preserve its "stringness".
Wikipedia's YAML article has a nice example showing how data types are supposed to be disambiguated.
You can tweak all the instances of zipcode
in the YAML before parsing it doing something like:
require 'yaml'
yaml_data = '2185:
id: 3274
civility: Mr
address: CROIX DES COMBES
zipcode: 04270
'
yaml_data.gsub(/zipcode: (\d+)/, 'zipcode: "\1"')
# => "2185:\n id: 3274 \n civility: Mr \n address: CROIX DES COMBES \n zipcode: \"04270\"\n"
YAML.load(yaml_data.gsub(/zipcode: (\d+)/, 'zipcode: "\1"'))
# => {2185=>{"id"=>3274, "civility"=>"Mr", "address"=>"CROIX DES COMBES", "zipcode"=>"04270"}}