Search code examples
rubyjsonrest-client

Ruby JSON response weird escaped characters


confused here. First time using RestClient over HTTParty. But when I make a request, I'm getting a

response = RestClient.get(url, :content_type => :json, :accept => :json, :'authorization' => token)

=> "{\"items\":[{\"tag\":\"#R0YL2RP\"},{\"tag\":\"#8U9PVV0R\"}]}"

So what's up with all the \? And how do I get rid of them?


Solution

  • You got the response printed to the console, as the result of evaluation of a REPL expression. This display is printed using #inspect, which, for strings, gives the representation of the string itself (so you can just plop it into the code); in this representation, backslashes and double quotes are escaped:

    "foo" + "bar"
    #  => "foobar"       - note the quotes
    

    If you print the string itself, you don't get it escaped:

    puts "foo" + "bar"
    # foobar            - note: no quotes
    #  => nil           - return value of `puts`
    

    If your string contains quotes:

    puts "\""
    # "
    #  => nil
    
    "\""
    #  => "\""
    

    Your JSON is fine - just getting escaped in printing. Do puts response instead of just response and see.