2

have URl want to store json data to database automatically

site provide this code but use Java

HttpResponse response = Unirest.get("https://xproject.restdb.io/rest/data")
  .header("x-apikey", "42ba8a6dc7532aa8319a58310281665e394e4")
  .header("cache-control", "no-cache")
  .asString(); 

This Example of json

enter image description here

model called speed contain speed & id
need save gps_speed_kph = speed & id_watch ==_id

Sdadad
  • 111
  • 1
  • 1
  • 9

2 Answers2

4

Firstly, you have to specify the db column data type as hash in your model as described here.

Then you have to save your json as hash in your db (json to hash ):

require 'json'
value = '{"val":"test","val1":"test1","val2":"test2"}'
myhash = JSON.parse(value)
Model.create(hash_column_name: myhash)

and for converting you can do this (hash to json):

@myhash = Model.find(1).hash_column_name
json_data = @myhash.to_json
Afsanefda
  • 3,069
  • 6
  • 36
  • 76
3

You can use JSONB column. This may help you to update the single are the group of data based on the key in the column.

Ref:

1) http://edgeguides.rubyonrails.org/active_record_postgresql.html#json-and-jsonb

2) https://nandovieira.com/using-postgresql-and-jsonb-with-ruby-on-rails

Gokul P
  • 444
  • 1
  • 5
  • 18
  • Thanks this link is useful but how can get data from request and pass it – Sdadad Jun 24 '18 at 14:50
  • In above question, you show this is from external API call for that refer Net::HTTP[https://ruby-doc.org/stdlib-2.4.1/libdoc/net/http/rdoc/Net/HTTP.html] methods. Then parse the response and store into the database. – Gokul P Jun 24 '18 at 15:57
  • I can't get of data from url ? – Sdadad Jun 25 '18 at 16:32
  • Check first whether your requesting URL giving the data or not. For example, following URL will give the JSON result https://obscure-dawn-93833.herokuapp.com/api/appointments – Gokul P Jun 26 '18 at 10:26
  • Thanks @Gokul p id don't know write any things explain what write ? – Sdadad Jun 26 '18 at 14:34