2012-03-02 138 views
1

我在獲取令牌後請求用戶在Facebook中的詳細信息。我得到了以下回應。 響應如下刪除字符串中的斜槓

"{\"id\":\"xxxxx\",\"name\":\"abcd\",\"first_name\":\"ab\",\"last_name\":\"cd\", 
\"link\":\"http:\\/\\/www.facebook.com\\/profile.php?id=xxxxx\",\"quotes\":\"Life is a difficult game. You can win it only by retaining your birthright to be a person.\",\"gender\":\"female\",\"timezone\":5.5,\"locale\":\"en_US\",\"verified\":true,\"updated_time\":\"2012-02-22T12:59:39+0000\"}" 

我印刷類響應表示爲"String"。我想把它改成一個散列。 (我想刪除上面的\)。

我試過但沒有得到正確的格式。

回答

8

這就是JSON。你只需要解析它。

require 'json' 

JSON.parse("{\"id\":\"xxxxx\",\"name\":\"abcd\",\"first_name\":\"ab\",\"last_name\":\"cd\", 
\"link\":\"http:\\/\\/www.facebook.com\\/profile.php?id=xxxxx\",\"quotes\":\"Life is a difficult game. You can win it only by retaining your birthright to be a person.\",\"gender\":\"female\",\"timezone\":5.5,\"locale\":\"en_US\",\"verified\":true,\"updated_time\":\"2012-02-22T12:59:39+0000\"}") 

#=> {"id"=>"xxxxx", "name"=>"abcd", "first_name"=>"ab", "last_name"=>"cd", "link"=>"http://www.facebook.com/profile.php?id=xxxxx", "quotes"=>"Life is a difficult game. You can win it only by retaining your birthright to be a person.", "gender"=>"female", "timezone"=>5.5, "locale"=>"en_US", "verified"=>true, "updated_time"=>"2012-02-22T12:59:39+0000"} 
+0

我想這很可能是寫它。工作正常。謝謝 – visnu 2012-03-02 11:56:54

4

您得到的響應是一個JSON對象。將其解析爲散列的最簡單方法是使用JSON gem。以下是字符串中前幾個實體的示例。正如你所看到的,它只是返回一個散列。

ruby-1.9.3-rc1 :001 > require 'json' 
=> true 
ruby-1.9.3-rc1 :002 > JSON.parse("{\"id\":\"xxxxx\",\"name\":\"abcd\",\"first_name\":\"ab\"}") 
=> {"id"=>"xxxxx", "name"=>"abcd", "first_name"=>"ab"} 
+0

對不起,我沒有注意到你的迴應:) – p0deje 2012-03-02 11:46:12

+0

不用擔心,我們在同一時間:) – 2012-03-02 11:50:18