Search code examples
rubyparsingresponse

Get values from server response in ruby


I send request to server and server returns me response. If I print this response, it looks exactly as mentioned below (with array and braces). I'm new to Ruby so I have two questions: 1. To what structure should I add this response? 2. How to I get values from this response (eg value of user_id or user_status). How to get rid of quotes in value

Request code:

def userGet(user_id_or_email)
uri = URI(SRV + '/userGet')
http = Net::HTTP.new(uri.host,uri.port)
req = Net::HTTP::Post.new(uri.path)
req['bla-bla'] = 'bla-bla'
req.set_form_data('search' => user_id_or_email)
res = http.request(req)
puts(res.read_body)
end

Output of puts(res)

array (
  'user_id' => 301877459,
  'login' => '0301877459',
  'email' => 'YS5raG96eWFfdHZhc2lsaWlAY29ycC5iYWRvby5jb20=',
  'passwd' => 'cc03e747a6afbbcbf8be7668acfebee5',
  'partner_id' => '105',
  'user_status' => 'active',
  'nickname' => 'Test',
  'fullname' => 'Test',
)

Solution

  • As other commentors have mentioned, the first step is to determine the encoding of the response. If you can easily change the way that the data is returned by the server, you could output valid JSON and use a gem such as this. If you cannot, then an ad-hoc method for parsing responses of this type would be to define a function like this:

    def parseResult(res)  
      # Remove the array wrapper and any leading/trailing whitespace
      parsed_string = res.gsub(/^\s*array\s*\(/, "").gsub(/[\s,]*\)[\s,]*$/, "")
    
      # Split the string into an array of key-value tuples
      parsed_array = parsed_string.split(',').collect do |tuple|
        tuple.split("=>").collect do |x|
          x.match(/^[\s',]*([^',]*)[\s',]*$/)[1]
        end 
      end
    
      # Convert the array of tuples into a hash for easy access
      Hash[parsed_array]
    end
    

    This is similar sawa's method, but it assumes that you cannot trust the data being returned by the server and therefore cannot use eval safely.