Remove back slash in string

巧了我就是萌 提交于 2019-12-24 10:47:22

问题


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.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/9532527/remove-back-slash-in-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!