删除字符串中的反斜杠

时间:2012-03-02 11:28:33

标签: ruby string hash

我在获取令牌后在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"。我想把它改成哈希。 (我想删除上面的\。)

我试过但没有得到正确的格式。

2 个答案:

答案 0 :(得分: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"} 

答案 1 :(得分: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"}