将尾随逗号和括号添加到Ruby JSON

时间:2016-03-23 21:51:37

标签: ruby-on-rails json regex

我需要在哈希之间添加逗号并将它们封装在方括号内。谁能告诉我怎么样?

这是我的代码:

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 个答案:

答案 0 :(得分: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