1

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?

Tudor Constantin
  • 26,330
  • 7
  • 49
  • 72
Shanib
  • 155
  • 1
  • 3
  • 13
  • u need to serialize it then insert it into the database. – Anil Dec 02 '11 at 10:54
  • what's the point to serialize it if you've got a model / table with matching attributes / columns ? here's a similar question that should help : http://stackoverflow.com/questions/1826727/how-do-i-parse-json-with-ruby-on-rails – m_x Dec 02 '11 at 11:49

1 Answers1

1

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"]).

Álvaro
  • 269
  • 1
  • 9