【问题标题】:How do I return specific json keys/values from an API after a search, using the HTTParty gem?如何在搜索后使用 HTTParty gem 从 API 返回特定的 json 键/值?
【发布时间】:2019-09-13 22:32:58
【问题描述】:

目前我有一个使用外部 API 并允许用户查询和返回 json 的简单应用程序。它返回所有键/值,但我只希望它在 json 中返回 lat 和 lon,或者至少我只想在我的视图中显示这两个。这是我的代码:

locationiq_api.rb

class LocationiqApi
  include HTTParty

  BASE_URI = "https://eu1.locationiq.com/v1/search.php"

  attr_accessor :city

  def initialize(api_key, format = "json")
    @options = { key: api_key, format: format }
  end

  def find_coordinates(city)
    self.class.get(BASE_URI, query: @options.merge({ q: city }))
  end

  def handle_error
    if find_coordinates.code.to_i = 200
      find_coordinates.parsed_response
    else
      raise "Couldn't connect to LocationIQ Api"
    end
  end
end 

locations_controller.rb

class LocationsController < ApplicationController

  def index
    @search = LocationiqApi.new("pk.29313e52bff0240b650bb0573332121e").find_coordinates(params[:q])
  end
end

locations.html.erb

<main>
  <h1>Location Search</h1>
  <!-- Button to search find coordinates -->
  <%= form_tag(locations_path, method: :get) do %>
    <%= label_tag(:q, "Search: ") %>
    <%= text_field_tag(:q) %>
    <%= submit_tag("Find coordinates") %>
  <% end %><br>

  <h2>Search results:</h2>

</main>

<%= @search %>

返回的json:

[{"place_id":"100066","licence":"https:\/\/locationiq.com\/attribution","osm_type":"node","osm_id":"107775","boundingbox":["51.3473219","51.6673219","-0.2876474","0.0323526"],"lat":"51.5073219","lon":"-0.1276474","display_name":"London, Greater London, England, SW1A 2DX, United Kingdom","class":"place","type":"city","importance":0.9654895765402,"icon":"https:\/\/locationiq.org\/static\/images\/mapicons\/poi_place_city.p.20.png"}]

【问题讨论】:

  • API 返回的 JSON 是什么样的?
  • @jvillian 我现在已将其添加到问题中。

标签: ruby-on-rails ruby geocoding rails-api httparty


【解决方案1】:

假设您有一个 JSON 字符串,例如,如下所示:

"[{\"place_id\":\"100066\",\"lat\":\"51.5073219\",\"lon\":\"-0.1276474\",\"class\":\"place\",\"type\":\"city\"}]"

那么你应该可以(粗略地说):

JSON.dump(
  JSON.
    parse(
      "[{\"place_id\":\"100066\",\"lat\":\"51.5073219\",\"lon\":\"-0.1276474\",\"class\":\"place\",\"type\":\"city\"}]"
    ).
    first.
    slice('lat', 'lon')
)

这应该给你:

 => "{\"lat\":\"51.5073219\",\"lon\":\"-0.1276474\"}" 

现在,我记得 HTTParty 可能已经将 API 响应转换为 Ruby 对象(数组或哈希),因此可能不需要 JSON.dump。而且,您可能还想做其他的事情(例如,如果您更喜欢将符号用作键而不是字符串,则可以使用 with_indifferent_access)。

要明确一点,如果您希望它成为您的类方法的一部分,那么您可以执行以下操作:

class LocationiqApi
  include HTTParty

  BASE_URI = "https://eu1.locationiq.com/v1/search.php"

  attr_accessor :city

  def initialize(api_key, format = "json")
    @options = { key: api_key, format: format }
  end

  def find_coordinates(city)
    JSON.dump(
      JSON.
        parse(
          self.class.get(BASE_URI, query: @options.merge({ q: city }))
        ).
        first.
        slice('lat', 'lon')
    )
  end

  def handle_error
    if find_coordinates.code.to_i = 200
      find_coordinates.parsed_response
    else
      raise "Couldn't connect to LocationIQ Api"
    end
  end
end

如果self.class.get(BASE_URI, query: @options.merge({ q: city })) 返回的不是表示hashes 的array 的有效JSON 字符串,那么这可能会失败。

我想关键位是:

  • 您需要将您的 JSON 转换(解析)为 Ruby 可以使用的东西;
  • 解析后,您需要从 array 的哈希中获取 hash(假设哈希数组始终是解析的结果);
  • 您可以使用slice 仅使用您想要的那些键值对;
  • 然后,既然您规定要返回 JSON,您需要使用例如JSON.dump 将您的 Ruby 对象转回 JSON。我想你也可以使用to_json。让你的船浮起来。

【讨论】:

  • 感谢您的回答:) 那么在我的类方法中没有办法做到这一点吗?不知何故只获取lat 和lon 参数?似乎必须有一个更简单的解决方案——也许使用 HTTParty 以外的东西,它会返回 JSON 而不是 Ruby 对象。
  • 所有这些都绝对可以在你的类方法中发生。您是否可以仅获取lat 和lon 参数取决于API 支持什么——我对此一无所知。但是,如果您收到的 JSON 字符串具有比您想要的更多的属性,那么我看不出如果不进行一些解析、操作和转储,您将如何获得您想要的属性。
  • 我认为API 支持获取单个参数,但不是 100% 肯定。我对使用 API 还很陌生,所以目前有点学习曲线。
  • 我只是快速浏览了 API 文档。在我看来,您不能指定要返回的属性的子集。顺便说一句,出于好奇,为什么要在视图中显示 JSON?
  • 我正在做一个编码挑战,它规定我应该制作一个应用程序,以字符串形式接收地址并将其转换为坐标,并且端点应该具有“JSON格式的响应”
【解决方案2】:

试试这个:

@search.map {|r| {lat: r['lat'], lon: r['lon']} }

将是一个哈希数组

【讨论】:

  • @search.map {|r| {lat: r['lat'], lon: r['lon']} }.to_json 工作吗?
  • @ThorTL67 这会引发类型错误no implicit conversion of String into Integer
猜你喜欢
  • 2018-09-22
  • 1970-01-01
  • 2018-08-25
  • 1970-01-01
  • 1970-01-01
  • 2014-04-14
  • 2014-12-20
  • 2018-10-02
  • 1970-01-01
相关资源
最近更新 更多