如何将以json格式接收的数据保存到数据库?

时间:2011-12-02 10:51:44

标签: ruby-on-rails json

我有一个用于iPhone应用程序的rubyonrails后端 webservice以json格式接收数据

例如:

[
 {"created_at":"2011-11-28T12:53:25Z","body":"good article","updated_at":"2011-11-23T12:53:30Z","id":1,"commenter":"shanib","user_id":1},
 {"created_at":"2011-11-28T07:29:53Z","body":"dfasdf","updated_at":"2011-11-28T07:29:53Z","id":2,"commenter":"dasf","user_id":1},
 {"created_at":"2011-11-28T08:36:37Z","body":"","updated_at":"2011-11-28T08:36:37Z","id":3,"commenter":"","user_id":1},
 {"created_at":"2011-11-28T12:41:18Z","body":"qwewqe","updated_at":"2011-11-28T12:41:18Z","id":4,"commenter":"Allen","user_id":1}
]

我如何解析这个json并使用循环

保存到数据库中

您能提供任何参考链接或演示吗?

1 个答案:

答案 0 :(得分:1)

您可以使用'json'宝石。 (现在已经与rails 3.1.x一起安装了。)

例如:

json_data = '[
 {"created_at":"2011-11-28T12:53:25Z","body":"good article","updated_at":"2011-11-23T12:53:30Z","id":1,"commenter":"shanib","user_id":1},
 {"created_at":"2011-11-28T07:29:53Z","body":"dfasdf","updated_at":"2011-11-28T07:29:53Z","id":2,"commenter":"dasf","user_id":1},
 {"created_at":"2011-11-28T08:36:37Z","body":"","updated_at":"2011-11-28T08:36:37Z","id":3,"commenter":"","user_id":1},
 {"created_at":"2011-11-28T12:41:18Z","body":"qwewqe","updated_at":"2011-11-28T12:41:18Z","id":4,"commenter":"Allen","user_id":1}
]'

data = JSON.parse(data)

会给你一个你可以迭代的哈希值。 (并且您可以使用类似数据[0] [“created_at”])来访问这些值。