0

I have set out on the task of learning ruby/rails and accessing API's with Ruby. I have a quick question:

I am making a GET request which returns JSON. Once I get that JSON back I need to be able to organize it so I can pull out what I want...However, the JSON comes back as an array with a hash inside. So, response.body returns what you see below. Response[0] gives me all of the JSON that makes up my request and leaves off the "13". Response[1] gives me just 13. How can I get, for example, the id for each survey without all of the excess JSON?

{ "surveys": [ { "status": "live", "responses": 2, "creator": "Service Organizer", "updated_at": "2013-07-10T22:16:23+00:00", "deploy_uri": "link", "responses_url": "link", "id": 221584, "name": "Test Email", "created_at": "2013-07-10T19:54:32+00:00", "uri": "link", "report_url": "link", "edit_url": "link" }, { "status": "live", "responses": 2, "creator": "Service Organizer", "updated_at": "2013-07-10T22:16:23+00:00", "deploy_uri": "link", "responses_url": "link", "id": 221584, "name": "Test Email", "created_at": "2013-07-10T19:54:32+00:00", "uri": "link", "report_url": "link", "edit_url": "link" } ], "total": 13 }

1 Answers1

0

For example, to collect the ids:

survey_ids = response.body["surveys"].map { |s| s["id"] }

For this to work, you have to convert the JSON string to Ruby format with JSON.parse per Dan Singerman's comment.

lurker
  • 56,987
  • 9
  • 69
  • 103
  • That makes sense, but I'm getting the following error: undefined method `map' for "surveys":String (NoMethodError) Any ideas? –  Jul 22 '13 at 16:09
  • The hash you gave actually isn't valid Ruby hash syntax. I updated my response accordingly. – lurker Jul 22 '13 at 16:18
  • Parse your JSON to a ruby hash first with JSON.parse(response.body) – DanSingerman Jul 22 '13 at 16:22
  • Indeed. I am using the HTTParty gem and was under the understanding that the JSON was already ready to rock when I got it. I used JSON.parse() and the code above worked fine. Thanks for the help! –  Jul 22 '13 at 16:26