简体   繁体   中英

Issue accessing hash inside of an array with Ruby

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 }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM