简体   繁体   中英

Parsing Data from httpparty response

I am returning quite a lot of JSON from a http party request

In my Rails controller I got this data:

 @data = @request.parsed_response["InfoResponses"]

and in my html.erb I displayed the @data on screen and it is as below:

[{"AdditionalResponse"=>nil, "AddressResponse"=>nil, "HighResResponse"=>nil, "LowResResponse"=>nil, "OtherResponse"=>nil, "Error"=>nil, "CarResponse"=>{"Values"=>[{"FieldDescription"=>"Colour", "FieldName"=>"COLOUR", "Value"=>BLUE}, {"FieldDescription"=>"Engine Size", "FieldName"=>"ENGINESIZE", "Value"=>1400}, {"FieldDescription"=>"Number Doors", "FieldName"=>"NUMBERDOORS", "Value"=>4}, {"FieldDescription"=>"Fuel", "FieldName"=>"FUEL", "Value"=>GAS}, {"FieldDescription"=>"Wheel Size", "FieldName"=>"WHEELSIZE", "Value"=>17}, {"FieldDescription"=>"CD Player", "FieldName"=>"CDPLAYER", "Value"=>Y}], 
"Error"=>nil, "Id"=>"2"}, "Id"=>"2", "DensityResponse"=>nil, "RiskIndexResponse"=>nil, "FinanceResponse"=>{"Value"=>Available, "Error"=>nil, "Id"=>"2"}}, 

{"AdditionalResponse"=>nil, "AddressResponse"=>nil, "HighResResponse"=>nil, "LowResResponse"=>nil, "OtherResponse"=>nil, "Error"=>nil, "CarResponse"=>{"Values"=>[{"FieldDescription"=>"Colour", "FieldName"=>"COLOUR", "Value"=>RED}, {"FieldDescription"=>"Engine Size", "FieldName"=>"ENGINESIZE", "Value"=>1400}, {"FieldDescription"=>"Number Doors", "FieldName"=>"NUMBERDOORS", "Value"=>4}, {"FieldDescription"=>"Fuel", "FieldName"=>"FUEL", "Value"=>GAS}, {"FieldDescription"=>"Wheel Size", "FieldName"=>"WHEELSIZE", "Value"=>19}, {"FieldDescription"=>"CD Player", "FieldName"=>"CDPLAYER", "Value"=>Y}], 
"Error"=>nil, "Id"=>"1"}, "Id"=>"1", "DensityResponse"=>nil, "RiskIndexResponse"=>nil, "FinanceResponse"=>{"Value"=>Available, "Error"=>nil, "Id"=>"1"}}]

On screen I only want to Display the CarResponse Details - ie all the Fields such as Colout, EngineSize, etc and their values and the only other details I want to extract are the FinanceResponse the Value and the Id.

What is the best way to extract these details - I have shown 2 here but my JSON response could include the same response as above repeated.

EDIT - My HttpParty code is as below

def self.GetInforFromASPWebAPI
 @request_body = [{:Id => '1',
                    :A => '1',
                    :B => '1',
                    :C=> '1'}]

    post('localhost:50544/api/MyController/GetInfo', :body => @request_body.to_json,
                                     :headers => {'Content-Type' => 'application/json'})
end

This is in a Helper class - then in my controller I was doing something like the below:

@response = ASPWebAPIClass.GetInforFromASPWebAPI

The contents of the response was even more data so I used what I had done before to strip some of it down to the parsed_response.

You should have a full class representing the API. Your methods would then get what you're interested in, rather than passing an entire response back to the Rails controller forcing the controller to know how to parse the API's response. Put all the API knowledge into the API class in accordance with the Single Responsibility Principle. Your code will be cleaner as a result.

Example:

class CarAPI
  include HTTParty
  base_uri 'localhost:50544/api/MyController'
  # any other initialization stuff

  def initialize
    @options = {
       :body => @request_body.to_json,
       :headers => {'Content-Type' => 'application/json'}
    }
  end

  def car_info
    response = self.class.post '/getinfo'

    # Create a simple Ruby hash with key/value pairs
    cars = {}
    response['InfoResponses'][0]['CarResponses']['Values'].each do |field|
      cars[field['FieldName']] = field['Value']
    end
    cars 
  end
end

This is a bit simplified; you'll want to iterate over all the responses (replace the [0] with a loop/map).

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