我想从yaml(PHPMyAdmin)中的Mysql转储中获取数据,但数据不是用引号括起来的。
我有可以从0开始的邮政编码,解析后我得到八进制值的十进制版本,代替简单的字符串。
如何强制Yaml解析器不进行自动映射,或只是获取所有数据,因为它们是字符串?
谢谢
==更新==
2185: id: 3274 civility: Mr address: CROIX DES COMBES zipcode: 04270I 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最满意答案
如果你的zipcode值是字符串,它们可能应该在数据库中,并且它们被正确转换为YAML,那么它们将被Ruby的YAML解析器重新转换回字符串:
require 'yaml' zip = '01234'如果我们将其视为字符串,则会正确转换。
zip.to_yaml # => "--- \"01234\"\n" YAML.load(zip.to_yaml) # => "01234"如果我们将它视为一个整数,它的前导0下降,这是我所期待的。
zip.to_i.to_yaml # => "--- 1234\n" YAML.load(zip.to_i.to_yaml) # => 1234在你的样本中:
zipcode: 04270zipcode是YAML整数。 它应该用引号括起来以保持其“字符串”。
维基百科的YAML文章有一个很好的例子,展示了如何消除数据类型的歧义。
您可以在解析之前调整YAML中所有zipcode实例,例如:
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"}}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) # => 1234In your sample:
zipcode: 04270zipcode 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"}}更多推荐
发布评论