0

我向服务器发送请求,服务器返回响应。如果我打印此响应,它看起来与下面提到的完全一样(带有数组和大括号)。我是 Ruby 新手,所以我有两个问题: 1. 我应该将此响应添加到什么结构中?2. 如何从该响应中获取值(例如 user_id 或 user_status 的值)。如何摆脱价值引号

请求代码:

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

puts(res) 的输出

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

2 回答 2

2

正如其他评论者所提到的,第一步是确定响应的编码。如果您可以轻松更改服务器返回数据的方式,则可以输出有效的 JSON 并使用诸如this之类的 gem 。如果你不能,那么解析这种类型的响应的临时方法是定义一个这样的函数:

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

这与sawa的方法类似,但它假设您不能信任服务器返回的数据,因此无法安全地使用 eval。

于 2012-11-28T21:17:14.457 回答
1

不知道这array ( ... )意味着什么,但假设它意味着一个哈希,你可以这样做:

string.eval(
  string
  .sub(/\A\s*array\s*\(/, "{")
  .sub(/\)\s*\z/, "}")
)
于 2012-11-28T09:56:51.023 回答