Saving JSON data to Database Rails from url

2019-08-05 08:33发布

问题:

I have a url which has been supplied which data is updated every 30 mins and wondering if i can save the data to my database as it updates? I'm using Rails 4.2.0.

There a 10 url's all up, each with a different unit number, which needs to be reference to be able to call each data for each unit.

URL structure

http://sitename/cgi-bin/site=1

JSON structure

{"status"=>"ok", "data"=>[{"2014-08-11 11:00:00"=>14.9},{"2014-08-11 11:30:00"=>15.1}]}

回答1:

With your json response, it can be done with something like this:

json = JSON.parse('{"status"=>"ok", "data"=>[{"2014-08-11 11:00:00"=>14.9},{"2014-08-11 11:30:00"=>15.1}]}') #string representing your json

json['data'].each do |element|
  element.each do |key, value|
    Model.create(date: key, number: value) # This Model is the name of your model
  end
end

If you let me suggest you something, You can send json as:

{"status"=>"ok", "data"=>[{"date" => "2014-08-11 11:00:00", "number" =>14.9},{...}]}

So you can access data like: element['date'] and element['number']



回答2:

I think you should go for crone jobs. Refer this Whenever gem that provides a clear syntax for writing and deploying cron jobs and you would save your data on every 30 mins into the database.