0

我正在尝试使用 Soulmate 进行搜索和自动完成。但是,它需要一个 json 文件,其中包含模型下的所有数据,并且每行一个项目。当我用 to_json 导出时,我得到所有用逗号分隔的对象。

这就是我要打印的内容:

{"id":1,"term":"Dodger Stadium","score":85,"data":{"url":"\/dodger-stadium-tickets\/","subtitle":"Los Angeles, CA"}}
{"id":28,"term":"Angel Stadium","score":85,"data":{"url":"\/angel-stadium-tickets\/","subtitle":"Anaheim, CA"}}
{"id":30,"term":"Chase Field ","score":85,"data":{"url":"\/chase-field-tickets\/","subtitle":"Phoenix, AZ"}}
{"id":29,"term":"Sun Life Stadium","score":84,"data":{"url":"\/sun-life-stadium-tickets\/","subtitle":"Miami, FL"}}
{"id":2,"term":"Turner Field","score":83,"data":{"url":"\/turner-field-tickets\/","subtitle":"Atlanta, GA"}}

这就是我用 to_json 打印的

[{"id":1,"first_name":"Philip","last_name":"nalle","location":"nallemia","email":"hejsan@hej.com","active":false,"created_at":"2013-06-26T15:00:38.990Z","updated_at":"2013-06-26T15:00:38.990Z"},{"id":2,"first_name":"Philip","last_name":"nalle","location":"hejsan123","email":"hejsan@asd.com","active":false,"created_at":"2013-06-26T15:01:45.905Z","updated_at":"2013-06-26T15:01:45.905Z"},{"id":3,"first_name":"hejsan","last_name":"hejsan","location":"asd","email":"asd@asda.com","active":false,"created_at":"2013-06-26T15:08:20.354Z","updated_at":"2013-06-26T15:08:20.354Z"},{"id":4,"first_name":"well well","last_name":"hello","location":"asd123","email":"asd@asd.com","active":false,"created_at":"2013-06-26T15:10:27.121Z","updated_at":"2013-06-26T15:12:29.991Z"}]

不要介意 json 中的实际数据,我只是从灵魂伴侣自述文件中复制了一个示例。这是 rake 任务。

desc "Save all participants to json"
task :save_to_json => :environment do
    File.open("participants.json", "w") { |f| f.write(Participant.all.to_json)} 
end
4

1 回答 1

1

要实现你想要的,你需要一个一个地输出元素。如果它们有很多,而不是 .all 你将它们抓取 1000,它也会节省内存。

desc "Save all participants to json"
task :save_to_json => :environment do
    File.open("participants.json", "w") do |f| 
        Participant.all.each do |participant| 
            f.write("#{participant.to_json}\n")
        end
    end
end
于 2013-06-27T10:04:37.093 回答