2016-03-23 16 views
1

私のハッシュの間にカンマを追加し、それらを大括弧で囲む必要があります。誰も私にどのように教えてくれますか?ここで末尾のカンマとブラケットをRuby JSONに追加

は私のコードです:ここでは

namespace :fieldfacts do 
    desc "Export Topics" 
    task :export_topics => :environment do 
    out = [] 
    File.open("public/topics.json","w") do |f| 
     Topic.all.each do |topic| 
      api = TopicsService.new() 
      topic_api = api.get(topic.topic_api_id) 
      out = { 
      'id' => topic.id, 
      'name' => topic.name, 
      'keywords_list' => topic_api.keywords_list, 
      'organizations_list' => topic_api.organizations_list, 
      'social_groups_list' => topic_api.social_groups_list, 
      'feeds_list' => topic_api.feeds_list, 
      'articles_list' => topic_api.articles_list, 
      'people' => topic_api.people 
      } 
     f.write(JSON.pretty_generate(out)) 
     end 
    end 
    end 
end 

が出力されます。

{ 
    "id": 3, 
    "name": "Precision Agriculture", 
    "keywords_list": null, 
    "organizations_list": null, 
    "social_groups_list": null, 
    "feeds_list": null, 
    "articles_list": null, 
    "people": null 
}{ 
    "id": 4, 
    "name": "Backcountry Skiing", 
    "keywords_list": null, 
    "organizations_list": null, 
    "social_groups_list": null, 
    "feeds_list": null, 
    "articles_list": null, 
    "people": null 
} 

任意の助けをいただければ幸いです。ありがとう!

+1

あなたは「ハッシュ間のカンマ」、ハッシュの配列のいくつかの並べ替えによって何を意味するのか、詳しく説明してください? –

+1

上記の出力は2つのハッシュを示しています。ハッシュは{}でカプセル化されています。通常のjsonファイルは各ハッシュをコンマで区切ります。 @MattSandersは答えを提供しました。ご協力いただきありがとうございます。 –

答えて

1

ここで問題となるのは、JSONを複数回生成してから、一度生成するのではなく、それをまとめて追加することです。このような

何かが(f.writeの位置の変化に注意してください)あなたの問題を解決する必要があります

namespace :fieldfacts do 
    desc "Export Topics" 
    task :export_topics => :environment do 
    out = [] 
    File.open("public/topics.json","w") do |f| 
     Topic.all.each do |topic| 
     api = TopicsService.new() 
     topic_api = api.get(topic.topic_api_id) 
     out << { 
      'id' => topic.id, 
      'name' => topic.name, 
      'keywords_list' => topic_api.keywords_list, 
      'organizations_list' => topic_api.organizations_list, 
      'social_groups_list' => topic_api.social_groups_list, 
      'feeds_list' => topic_api.feeds_list, 
      'articles_list' => topic_api.articles_list, 
      'people' => topic_api.people 
     } 
     end 
     f.write(JSON.pretty_generate(out)) 
    end 
    end 
end 
+0

恐ろしい!すばやく正確な解決に感謝しています! –

+0

お手伝いします! :-) –

関連する問題