我有一个rails应用程序。 我通过Ajax调用获得了JSON数据,现在我想将我的JSON数据导入应用程序数据库。我该如何存档?谁能帮我?提前谢谢。
--- ---更新
我的应用程序有一个Task模型和User模型。用户有很多任务,任务属于用户。用户登录后,我将进行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 :(得分:19)
如果您还没有JSON gem,可以通过命令行安装它:
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