【问题标题】:Rails - Soulmate, export to json one item per lineRails - 灵魂伴侣,每行导出一个 json 项目
【发布时间】:2013-06-27 09:56:13
【问题描述】:

我正在尝试使用 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

【问题讨论】:

    标签: ruby-on-rails json rake ruby-on-rails-4


    【解决方案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-02-14
      • 2014-03-02
      • 2018-08-17
      • 1970-01-01
      • 2011-04-11
      • 2011-06-13
      • 1970-01-01
      • 2019-12-15
      • 1970-01-01
      相关资源
      最近更新 更多