Ruby 将twitter搜索结果保存到JSON文件

Ruby 将twitter搜索结果保存到JSON文件,ruby,twitter,Ruby,Twitter,我正在使用twitter ruby gem获取twitter搜索结果。Github的示例代码从搜索结果中提取信息。我想知道如何将搜索结果(我认为是JSON)保存到单独的JSON文件中。 下面是示例代码的一部分: results = @search.perform("$aaa", 1000) aFile = File.new("data.txt", "w") results.map do |status| myStr="#{status.from_user}: #{status.text} #{

我正在使用twitter ruby gem获取twitter搜索结果。Github的示例代码从搜索结果中提取信息。我想知道如何将搜索结果(我认为是JSON)保存到单独的JSON文件中。
下面是示例代码的一部分:

results = @search.perform("$aaa", 1000)
aFile = File.new("data.txt", "w")
results.map do |status|
myStr="#{status.from_user}: #{status.text}  #{status.created_at}"
aFile.write(myStr)
aFile.write("\n")
end
有没有办法将所有搜索结果保存到单独的JSON文件,而不是将字符串写入文件?

提前感谢。

如果要保存到文件,只需打开文件,将其写入,然后关闭:

File.open("myFileName.txt", "a") do |mFile|
    mFile.syswrite("Your content here")
    mFile.close
end
使用
open
时,如果文件不存在,则将创建该文件

需要注意的一点是,打开文件有不同的方法,其中的方法将决定程序写入的位置。
“a”
表示它会将您写入文件的所有内容附加到当前内容的末尾

以下是一些选项:

r   Read-only mode. The file pointer is placed at the beginning of the file. This is the default mode.
r+  Read-write mode. The file pointer will be at the beginning of the file.
w   Write-only mode. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
w+  Read-write mode. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
a   Write-only mode. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
a+  Read and write mode. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
因此,在您的情况下,您可能希望取出要保存的数据,然后将其写入一个文件,如我所示。您还可以通过执行以下操作来指定文件路径:

File.open("/the/path/to/yourfile/myFileName.txt", "a") do |mFile|
    mFile.syswrite("Your content here")
    mFile.close
end
另一件需要注意的事情是,
open
不创建目录,因此您需要自己创建目录,或者您可以使用程序来创建目录。以下是一个有助于文件输入/输出的链接:


Pro提示:使用而不是
文件。新建
和手动关闭。这使得关闭文件具有确定性和异常安全性。
JSON
只是格式化数据的一种方式。归根结底,这只是一根长长的绳子。您可以将数据保存到文件中,就像将其他文本保存到文件中一样。您不需要使用任何特殊的文件扩展名保存它。