Reputation: 135
How I convert this json var
email = {"email":"[email protected]"}
into this encoded string?
%7B%22email%22%3A%22name%40gmail.com%22%7D
Upvotes: 4
Views: 5239
Reputation: 183929
Use CGI.escape, NOT URI.encode/escape. URI.encode will not escape the brackets of JSON arrays.
emails = '{"list_1":[{"Jim":"[email protected]"},{"Joe":"[email protected]"}]}'
> URI::encode(emails)
=> "%7B%22list_1%22:[%7B%22Jim%22:%[email protected]%22%7D,%7B%22Joe%22:%[email protected]%22%7D]%7D"
> CGI.escape(emails)
=> "%7B%22list_1%22%3A%5B%7B%22Jim%22%3A%22jim%40gmail.com%22%7D%2C%7B%22Joe%22%3A%22joe%40gmail.com%22%7D%5D%7D"
ruby - What's the difference between URI.escape and CGI.escape - Stack Overflow
Upvotes: 1
Reputation: 15967
Sure you can use the uri
library shown here
[2] pry(main)> require 'uri'
=> true
[3] pry(main)> URI.encode('{"email":"[email protected]"}')
=> "%7B%22email%22:%[email protected]%22%7D"
Upvotes: 3