Remove back slash in string

2019-07-29 11:12发布

I am requesting user detail in facebook after getting token . I got the following response. Response as follows

"{\"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\"}"

I printed the class of response showing as "String". I want to change this into a hash. (I want to remove the \ in the above).

I tried but not get the correct format.

标签: ruby string hash
2条回答
女痞
2楼-- · 2019-07-29 11:49

That's JSON. You just need to parse it.

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"} 
查看更多
叛逆
3楼-- · 2019-07-29 11:52

The response you get is a JSON object. The easiest way to parse that into a hash is by using the JSON gem. Here's an example with the first few entities in your string. As you can see it just returns a hash.

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"}
查看更多
登录 后发表回答