简体   繁体   中英

Return specific values from array of hashes - JSON

Hi am learning rails and in my app, I'm getting values in json format from
res = @client.spots(params[:location][:lat], params[:location][:lng], :types => ['restaurant','food'], :radius => 500)

in my res object, I'm getting these values

 { "json_result_object": { "business_status": "OPERATIONAL", "geometry": { "location": { "lat": 31.4734563, "lng": 74.2794873 }, }, "icon": "https://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png", "name": "CP Five Star", "opening_hours": { "open_now": true } } ], "place_id": "ChIJjfE-TdoDGTkRMom8KQfI9Uc", "plus_code": { "compound_code": "F7FH+9Q Lahore, Pakistan", "global_code": "8J3PF7FH+9Q" }, }, "reference": "ChIJjfE-TdoDGTkRMom8KQfI9Uc", "place_id": "ChIJjfE-TdoDGTkRMom8KQfI9Uc", "vicinity": "Bilal Arcade, Abdul Haque Road, Block G Block G Phase 1 Johar Town, Lahore", "lat": 31.4734563, "lng": 74.2794873, "viewport": { "northeast": { "lat": 31.4748154802915, "lng": 74.28081473029151 }, "southwest": { "lat": 31.4721175197085, "lng": 74.2781167697085 } }, "name": "CP Five Star", "icon": "https://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png", "types": [ "restaurant", "food", "point_of_interest", "establishment }

now I just want to return a JSON array containing just the values below place_id , name , lat lng , icon

& Sorry I'm using image just to show my actual response in terminal image

You can check what your res object type is by doing res.class ; if it is not a hash already, you can follow the steps here to convert it to hash.

with the res hash you can just return JSON Array like this -

[res["place_id"], res["name"], res["lat"], res["lng"], res["icon"]]

yes, at the end, I find the solution. res is an array and there are multiple hashes in this array, As I'm getting this from Google Places API, so if someone wants to access the name, latitude, longitude, place_id of nearby restaurants he can do it easily by .Map by the following code.

 resturants =res.map { |a| {id: a.place_id , name: a.name , lat: a.lat, lng: a.lng , icon: a.icon}} json_response "Successfully retrive data" , true, {Resturant: resturants }, :ok

Note: json_response is my function from application controller you can use render json as well.

More over if you want array of arrays you can do it easily by

 res.pluck(:name, :place_id , :lat , :lng, :icon)

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