2011-03-17 73 views
4

我有一個Rails應用程序。 我已經通過Ajax調用了JSON數據,現在我想我的JSON數據導入到應用數據庫。我怎樣才能存檔這個?誰能幫我?提前致謝。我可以導入JSON數據到數據庫,與我的Rails應用程序?

---更新---
我的應用程序有一個任務模式和用戶模式。用戶有很多任務,任務屬於一個用戶。用戶登錄後,我會讓Ajax調用(jQuery的的getJSON)從其他服務提供商處獲取JSON數據。我想將JSON數據作爲任務導入數據庫。

----添加樣品JSON數據----

{ 
    "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" 
} 
+0

如果您添加更多關於希望數據如何保存的詳細信息數據庫。這些數據是對應於一個模型還是隻想在MySQL數據庫中使用原始JSON數據? – 2011-03-17 16:54:29

+0

你好潘,我已經添加了更新信息。 – 2011-03-17 17:27:25

+0

這很有道理。感謝您提供最新信息。如果您將getJSON調用的樣本結果添加到您的問題中,則回答者可以爲您寫入代碼樣本以導入該數據。你在使用MySQL嗎? – 2011-03-17 17:49:55

回答

19

如果您還沒有的JSON的寶石,你可以通過命令行安裝:

gem install json 

這將允許您將JSON解析爲其等效的Ruby數據結構。

如果JSON已經符合你的模型,您需要做的僅僅是這樣的:

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

如果它不符合你的模型,你可以這樣做:

a_hash = JSON.parse(json_string_from_external_service) 

然後你只需複製您的屬性並保存:

new_record = Model.new 
new_record.attribute_1 = a_hash['key_for_attribute_1'] 
... etc ... 
new_record.save 
相關問題