Shanib
Shanib

Reputation: 155

How to save data received in json format to database?

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

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

Can you provide any reference links or demo?

Upvotes: 1

Views: 1102

Answers (1)

Álvaro
Álvaro

Reputation: 269

You can use the 'json' gem. (Which is now already installed together with 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"]).

Upvotes: 1

Related Questions