简体   繁体   English

从文件构建Ruby哈希

[英]Ruby Build Hash from file

I'm consuming a web-service and using Savon to do +-1000 (paid) requests and parse the requests to a csv file. 我正在使用Web服务,并使用Savon进行+ -1000(付费)请求并将请求解析为csv文件。 I save the xml.hash response in a file if the parsing failed. 如果解析失败,我将xml.hash响应保存在一个文件中。 How can I initialize an hash that was saved to a file? 如何初始化保存到文件中的哈希? (or should I save in XML and then let savon make it into a hash it again? (或者我应该保存为XML,然后让savon再次将其变成一个哈希吗?

Extra info: 额外信息:

client = Savon.client do
    wsdl "url"
end

response = client.call(:read_request) do 
  message "dat:number" => number 
end

I use the response.hash to build/parse my csv data. 我使用response.hash构建/解析我的csv数据。 Ex: 例如:

name = response.hash[:description][:name]

If the building failed I'm thinking about saving the response.hash to a file. 如果构建失败,我正在考虑将response.hash保存到文件中。 But the problem is I don't know how to reuse the saved response (XML/Hash) so that an updated version of the building/parsing can be run using the saved response. 但是问题是我不知道如何重用已保存的响应(XML /哈希),以便可以使用已保存的响应来运行构建/解析的更新版本。

You want to serialize the Hash to a file then deserialize it back again. 您想将Hash序列化为文件,然后再次将其反序列化。

You can do it in text with YAML or JSON and in a binary via Marshal . 您可以使用YAMLJSON以文本形式以及通过Marshal以二进制形式来实现。

Marshal 元帅

def serialize_marshal filepath, object
  File.open( filepath, "wb" ) {|f| Marshal.dump object, f }
end

def deserialize_marshal filepath
  File.open( filepath, "rb") {|f| Marshal.load(f)}
end

Marshaled data has a major and minor version number written with it, so it's not guaranteed to always load in another Ruby if the Marshal data version changes. 封送处理的数据具有主要和次要版本号,因此,如果封送处理的数据版本发生变化,则不能保证始终将其加载到另一个Ruby中。

YAML YAML

require 'yaml'

def serialize_yaml filepath, object
  File.open( filepath, "w" ) {|f| YAML.dump object, f }
end

def deserialize_yaml filepath
  File.open( filepath, "r") {|f| YAML.load(f) }
end

JSON JSON

require 'json'

def serialize_json filepath, object
  File.open( filepath, "w" ) {|f| JSON.dump object, f }
end

def deserialize_json filepath
  File.open( filepath, "r") {|f| JSON.load(f)}
end

Anecdotally, YAML is slow, Marshal and JSON are quick. 有趣的是,YAML速度很慢,Marshal和JSON速度很快。

If your code is expecting to use/manipulate a ruby hash as demonstrated above, then if you want to save the Savon response, then use the json gem and do something like: 如果您的代码期望使用/操作如上所示的ruby哈希,那么如果要保存Savon响应,请使用json gem并执行以下操作:

require 'json'

File.open("responseX.json","w") do |f| 
  f << response.hash.to_json 
end

Then if you need to read that file to recreate your response hash: 然后,如果您需要读取该文件以重新创建响应哈希:

File.open('responseX.json').each do |line|
  reponseHash = JSON.parse(line)
  # do something with responseHash
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM