简体   繁体   中英

Formatting JSON for bulk Keen.io upload

I am trying to setup a sample bulk upload to Keen.io using the ruby gem. From their docs:

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

My attempt at a rake task to generate something similar:

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

I get the following error:

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

I am sure I am just messing up the JSON output somehow, but I can't seem to figure out how/where?

Thanks!

This should work if you do not call .to_json on the array that you have created.

Try,

Keen.publish_batch(:jobs => jobs_array)

as opposed to what is currently stated

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

Hope this helps!

Here is the answer in case it helps anyone else....

   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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM