json 如何将对象保存到文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4310217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I save an object to a file?
提问by Flethuseo
I would like to save an object to a file, and then read it from the file easily. As a simple example, lets say I have the following 3d array:
我想将对象保存到文件中,然后轻松地从文件中读取它。作为一个简单的例子,假设我有以下 3d 数组:
m = [[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]]
Is there an easy Ruby API that I can use to achieve this without programming a parser to interpret the data from the file? In the example I give it is easy, but as the objects become more complicated, it gets annoying to make objects persistent.
是否有一个简单的 Ruby API 可以用来实现这一点,而无需编写解析器来解释文件中的数据?在我给出的例子中很容易,但是随着对象变得越来越复杂,让对象持久化变得很烦人。
采纳答案by Cory
回答by Swanand
You need to serialize the objects before you could save them to a file and deserialize them to retrieve them back. As mentioned by Cory, 2 standard serialization libraries are widely used, Marshaland YAML.
您需要先序列化对象,然后才能将它们保存到文件中并反序列化它们以检索它们。正如 Cory 所提到的,2 个标准序列化库被广泛使用,Marshal并且YAML.
Both Marshaland YAMLuse the methods dumpand loadfor serializing and deserializing respectively.
两者Marshal并YAML用的方法dump和load用于序列化和反序列化分别。
Here is how you could use them:
以下是您可以如何使用它们:
m = [
[
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]
],
[
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]
]
]
# Quick way of opening the file, writing it and closing it
File.open('/path/to/yaml.dump', 'w') { |f| f.write(YAML.dump(m)) }
File.open('/path/to/marshal.dump', 'wb') { |f| f.write(Marshal.dump(m)) }
# Now to read from file and de-serialize it:
YAML.load(File.read('/path/to/yaml.dump'))
Marshal.load(File.read('/path/to/marshal.dump'))
You need to be careful about the file size and other quirks associated with File reading / writing.
您需要注意与文件读取/写入相关的文件大小和其他怪癖。
More info, can of course be found in the API documentation.
更多信息,当然可以在 API 文档中找到。
回答by Andrew McGuinness
YAML and Marshal are the most obvious answers, but depending on what you're planning to do with the data, sqlite3may be a useful option too.
YAML 和 Marshal 是最明显的答案,但取决于您计划对数据做什么,sqlite3也可能是一个有用的选择。
require 'sqlite3'
m = [[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]]
db=SQLite3::Database.new("demo.out")
db.execute("create table data (x,y,z,value)")
inserter=db.prepare("insert into data (x,y,z,value) values (?,?,?,?)")
m.each_with_index do |twod,z|
twod.each_with_index do |row,y|
row.each_with_index do |val,x|
inserter.execute(x,y,z,val)
end
end
end

