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?

2
  • u need to serialize it then insert it into the database. Commented Dec 2, 2011 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 : stackoverflow.com/questions/1826727/… Commented Dec 2, 2011 at 11:49

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.