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

时间:2023-01-14 10:32:04

i have an rubyonrails backend for an iphone application the webservice receives data in json format

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

eg:

例如:

[
 {"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}
]

How can i parse this json and save into database using looping

我如何解析这个json并使用循环保存到数据库中

Can you provide any reference links or demo?

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

1 个解决方案

#1


1  

You can use the 'json' gem. (Which is now already installed together with rails 3.1.x).

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

For example:

例如:

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)

will give you a hash which you can iterate trough. (And you can access the values using like data[0]["created_at"]).

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

#1


1  

You can use the 'json' gem. (Which is now already installed together with rails 3.1.x).

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

For example:

例如:

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)

will give you a hash which you can iterate trough. (And you can access the values using like data[0]["created_at"]).

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