2011-03-17 72 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 
相关问题