Parsing XML HTTParty response

1.3k views Asked by At

I was getting data from an api using HTTParty. I managed to get back the XML response, and it looks like HTTParty has made that xml response into Ruby.

How can I navigate through the hashes and get the data I need? For instance, say I wanted the "Name", which is "29TH AVENUE STN/ARBUTUS".

The API key works fine, since I am getting a response back.

Just not too sure how I can navigate through and get the data I want, and to put it into my view.

index.html.erb:

<% @courses.each do |course| %>
<%= course %>

<% end %>

HTTparty response:

["Route", {
"RouteNo" => "016", "Name" => "29TH AVENUE STN/ARBUTUS ", "OperatingCompany" => "CMBC", "Patterns" => {
    "Pattern" => [{
        "PatternNo" => "E5TP", "Destination" => "29TH AVE STN", "RouteMap" => {
            "Href" => "http://nb.translink.ca/geodata/trip/016-E5TP.kmz"
        }, "Direction" => "EAST"
    }, {
        "PatternNo" => "EB1", "Destination" => "29TH AVE STN", "RouteMap" => {
            "Href" => "http://nb.translink.ca/geodata/trip/016-EB1.kmz"
        }, "Direction" => "EAST"
    }, {
        "PatternNo" => "EB5", "Destination" => "29TH AVE STN", "RouteMap" => {
            "Href" => "http://nb.translink.ca/geodata/trip/016-EB5.kmz"
        }, "Direction" => "EAST"
    }]
}
}]

Model for getting the response

class Checker

include HTTParty

base_uri 'http://api.translink.ca/rttiapi/v1/routes'
default_params apikey: "[my proper api key]"
format :xml

def self.for term
  get("", query: {stopNo: term})["Routes"]["Route"]["RouteNo"]
  end
end

Controller for the Model

  class TimesController < ApplicationController
  def index
    @search_term = '51048'
    @courses = Checker.for(@search_term)
  end
end
1

There are 1 answers

0
Aleksei Matiushkin On BEST ANSWER

Assuming you have a response shown:

resp = ["Route", {
"RouteNo" => "016", "Name" => "29TH AVENUE STN/ARBUTUS ", "OperatingCompany" => "CMBC", "Patterns" => {
    "Pattern" => [{
        "PatternNo" => "E5TP", "Destination" => "29TH AVE STN", "RouteMap" => {
            "Href" => "http://nb.translink.ca/geodata/trip/016-E5TP.kmz"
        }, "Direction" => "EAST"
    }, {
        "PatternNo" => "EB1", "Destination" => "29TH AVE STN", "RouteMap" => {
            "Href" => "http://nb.translink.ca/geodata/trip/016-EB1.kmz"
        }, "Direction" => "EAST"
    }, {
        "PatternNo" => "EB5", "Destination" => "29TH AVE STN", "RouteMap" => {
            "Href" => "http://nb.translink.ca/geodata/trip/016-EB5.kmz"
        }, "Direction" => "EAST"
    }]
}
}]

which is in turn an array of two elements, first being 'Route' and the last being a hash with all properties, to get the name use simply:

resp.last['Name']