格式化批量Keen.io上传的JSON

时间:2015-11-08 15:22:06

标签: ruby json keen-io

我正在尝试使用ruby gem设置一个示例批量上传到Keen.io。来自他们的文档:

Keen.publish_batch(
  :signups => [
    { :name => "Bob" },
    { :name => "Mary" }
  ],
  :purchases => [
    { :price => 10 },
    { :price => 20 }
  ]
)

我尝试用rake任务生成类似的东西:

task backfill_keen_jobs: :environment do

   jobs_array = Array.new
   Job.last(5).each do |j|
      job_type = j.job_type.present? ? j.job_type.description : nil
      job = {
         :keen => {
            :timestamp => j.created_at.to_time.iso8601
         },
         :id => j.id,
         :title => j.title,
         :type => job_type,
         :company => j.company

      }

      jobs_array << JSON.generate(job)

   end
   puts jobs_array
   puts Keen.publish_batch(:jobs => [jobs_array.to_json])
end

我收到以下错误:

{"jobs"=>[{"success"=>false, "error"=>{"name"=>"InvalidPropertyNameError", "description"=>"An event should be a JSON object of properties."}}]}

我确信我只是搞砸了JSON输出,但我似乎无法弄清楚如何/在哪里?

谢谢!

2 个答案:

答案 0 :(得分:1)

如果你没有在你创建的数组上调用.to_json,这应该可以工作。

尝试,

Keen.publish_batch(:jobs => jobs_array)

与目前陈述的相反

Keen.publish_batch(:jobs => [jobs_array.to_json])

希望这有帮助!

答案 1 :(得分:0)

以下是答案,以防其他人帮助....

   jobs_array = Array.new
   Job.last(5).each do |j|
      job_type = j.job_type.present? ? j.job_type.description : nil
      job = {
         :keen => {
            :timestamp => j.created_at.to_time.iso8601
         },
         :id => j.id.to_i,
         :title => j.title,
         :type => job_type,
         :company => j.company
      }

      jobs_array << job

   end
   jobs_array
   Keen.publish_batch(:jobs => jobs_array)