从哈希数组返回特定​​值-JSON

问题描述

我正在学习Rails,在我的应用中,我从JSON格式中获取了值
res = @client.spots(params[:location][:lat],params[:location][:lng],:types => ['restaurant','food'],:radius => 500)

在我的res对象中,我得到了这些值

{
  "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","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
    }
  },"types": [
    "restaurant","food","point_of_interest","establishment
  
}

现在我只想返回一个仅包含place_id,name,lat以下值的JSON数组 lng,图标

&抱歉,我使用的图像只是为了显示终端image上的实际响应

解决方法

您可以通过执行res.class来检查res对象的类型。如果还不是哈希,则可以按照here的步骤将其转换为哈希。

使用res哈希,您可以像这样返回JSON数组-

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

,

是的,最后我找到了解决方案。 res是一个数组,并且此数组中有多个哈希,正如我从Google Places API获取的那样,因此如果有人想访问附近餐厅的名称,纬度,经度,place_id,则可以通过.Map by以下代码。

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

注意:json_response是我从应用程序控制器发出的函数,您也可以使用render json。

此外,如果您想要数组数组,可以轻松实现

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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...