【问题标题】:Issues trying to return multiple JSON results with Rails API/front-end尝试使用 Rails API/前端返回多个 JSON 结果的问题
【发布时间】:2018-05-21 00:47:31
【问题描述】:

我有一个包含非营利信息的 API,我试图根据“类别”参数从中获取结果。基本上,我想遍历并返回该类别下每个非营利组织的名称、描述、地址、电话号码和网站。使用我一直采用的方法,我不断收到“没有将字符串隐式转换为整数”错误或“未定义方法 []”错误。非常感谢您的帮助!

控制器:

def index
   @homeless_organizations = Organization.get_homeless_organizations
end

服务

class Organization
  def self.get_homeless_organizations
   response = JSON.parse(RestClient.get('http://localhost:3001/organizations? 
   category=Homelessness'))
     response['name']['description']['address']['phone']['website'].each do   
     |response|
       puts response
       puts "#{response['name']['description']['address']['phone'] 
        ['website']}"
    end
  end

JSON 正文:

[
 {
    "id": 1,
    "name": "Transition Projects",
    "category": "Homelessness",
    "description": "Transition Projects delivers life-saving and life-changing assistance to some of Portland’s most vulnerable residents. Whether by helping a homeless veteran and her family find housing, sheltering hundreds of people each night with nowhere else to turn, or opening new pathways to employment, Transition Projects represents an invaluable part of Portland’s social fabric.",
    "address": "665 NW Hoyt St, Portland, OR 97209",
    "phone": "(503) 280-4700",
    "created_at": "2018-05-19T00:18:30.592Z",
    "updated_at": "2018-05-19T00:18:30.592Z",
    "website": "https://www.tprojects.org/"
 },
 {
    "id": 2,
    "name": "Portland Homeless Family Solutions",
    "category": "Homelessness",
    "description": "Giving hope to homeless families with children. Our mission is to empower homeless families with children to get back into housing - and stay there.",
    "address": "1221 SW Yamhill St #210, Portland, OR 97205",
    "phone": "(503) 915-8306",
    "created_at": "2018-05-19T00:18:30.600Z",
    "updated_at": "2018-05-19T00:18:30.600Z",
    "website": "http://pdxhfs.org/"
 },
 {
    "id": 3,
    "name": "Portland Rescue Mission",
    "category": "Homelessness",
    "description": "Food, shelter, clothing, mail service, restrooms, showers and other emergency services are available free of charge at Portland Rescue Mission's Burnside Shelter.",
    "address": "111 W Burnside St, Portland, OR 97209",
    "phone": "(503) 906-7690",
    "created_at": "2018-05-19T00:18:30.603Z",
    "updated_at": "2018-05-19T00:18:30.603Z",
    "website": "https://www.portlandrescuemission.org/.../food-shelter-services/"
 }
]

【问题讨论】:

  • response.each { |r| puts "#{r['name']} #{r['description']}" }
  • 你正在“隐藏”response 变量。

标签: ruby-on-rails json ruby rails-api


【解决方案1】:

解析 JSON 响应后,您最终会得到一个哈希数组。要从所有散列中获取值,您需要遍历该数组并在每个散列上为您想要的每个值调用 Hash#[] 方法。

response.each do |organization|
  p [organizations['name'], organization['description']]
end

由于您需要散列中的多个值,而不是一次调用一个(如上所述),您可以使用Hash#values_at 执行类似于您尝试的操作并获取所有值立即取出,在一个新数组中:

response.each do |organization|
  p organization.values_at('name', 'description')
end

至于你的代码有什么问题:

调用response['name'] 是调用Array#[],这与Hash#[] 不同,它需要一个整数索引来表示您想要访问的元素,所以如果您只想从第一个组织获取值,您可以已完成:

p [response[0]['name'], response[0]['description']]

但是你给它传递了一个字符串,这是它没有预料到的,所以你得到了TypeError (no implicit conversion of String into Integer)。 (这只是一个说明,使用each 比传递特定的索引更好,除非你只需要特定的索引。)

最后,当您像现在这样一个接一个地调用#[] 时,在第一个调用之后,您最终会在前一个调用的返回值上调用#[]。在这种情况下,如果您在数组内的哈希而不是数组本身上调用#[],您最终会调用String#[],这与Array#[]Hash#[] 不同。虽然它可以接受一个字符串或一个整数,但它不会做你想要的(如果给出了一个字符串,如果它存在于你调用#[] on 的字符串中,它会返回该字符串;如果给出一个整数,它会返回字符串中该位置的字符):

# "Transition Projects" is `response[0]['name']`
"Transition Projects"['description'] # => nil
"Transition Projects"['Proj'] # => "Proj"
"Transition Projects"[8] # => "o"

然后你最终要么在 nil (NoMethodError) 或另一个字符串上调用 #[]

【讨论】:

  • 啊,这成功了!非常感谢您的详细回答,我现在绝对觉得我对这个问题有了更好的整体理解。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-18
  • 2020-09-17
  • 1970-01-01
  • 1970-01-01
  • 2016-12-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多