Can I import JSON data into a database using my rails application?

I have one rails application. I have JSON data through an Ajax call, and now I want to import the JSON data into the application database. How can I archive this? Can someone help me? Thanks in advance.

--- Update ---
My application has a task model and a user model. The user has many tasks, and the task belongs to the user. After logging in, I will make an Ajax call (jQuery getJSON), receiving JSON data from another service provider. I want to import JSON data into a database as tasks.

---- Add Sample Json Data ----

{ "server_time":"2010-12-22 15:27:04 +0800", "entries":[ { "all_day":true, "archived":null, "assignment":null, "attribute":"plan", "completed":null, "context":null, "created":"2010-12-14 14:50:24 +0800", "deleted":null, "end_at":null, "forwarded_by":null, "id":"jee+ypfERGSCqlXjuyUjYw==", "notes":"", "priority":0, "project":null, "reminders":[], "repeat_no":null, "repeater":null, "start_at":"2010-12-14 00:00:00 +0800", "tags":[], "title":"xcv", "trashed":null, "updated":"2010-12-14 14:50:24 +0800", "hidden":null } ... { "all_day":true, "archived":null, "assignment":null, "attribute":"inbox", "completed":null, "context":null, "created":"2010-12-15 16:12:24 +0800", "deleted":null, "end_at":null, "forwarded_by":null, "id":"MOAvW5IBTXScMVq2WdXFXQ==", "notes":"", "priority":0, "project":"z1", "reminders":[], "repeat_no":null, "repeater":null, "start_at":null, "tags":[], "title":"3", "trashed":null, "updated":"2010-12-15 16:12:24 +0800", "hidden":null }, { "all_day":true , "archived":null, "assignment":null, "attribute":"plan", "completed":null, "context":null, "created":"2010-12-15 18:29:27 +0800", "deleted":null, "end_at":null, "forwarded_by":null, "id":"dSOHwcYQRbmTCO+wjtUUaQ==", "notes":"", "priority":0, "project":null, "reminders":[], "repeat_no":null, "repeater":null, "start_at":"2010-12-17 00:00:00 +0800", "tags":[], "title":"after day", "trashed":null, "updated":"2010-12-15 18:29:27 +0800", "hidden":null } ], "addtional":"full" } 
+4
source share
1 answer

If you don’t have a JSON pearl yet, you can install it via the command line:

 gem install json 

This will allow you to parse JSON into its equivalent Ruby data structures.

If the JSON already matches your model, you just need to do something like:

 new_record = Model.new(JSON.parse(json_string_from_external_service)) new_record.save 

If this still does not fit your model, you can do:

 a_hash = JSON.parse(json_string_from_external_service) 

Then you just copy your attributes and save:

 new_record = Model.new new_record.attribute_1 = a_hash['key_for_attribute_1'] ... etc ... new_record.save 
+19
source

Source: https://habr.com/ru/post/1344143/


All Articles