Question

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 }

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top