我如何转换此json var
email = {"email":"name@gmail.com"}
进入这个编码的字符串?
%7B%22email%22%3A%22name%40gmail.com%22%7D
答案 0 :(得分:3)
当然,您可以使用显示here
的uri
库
[2] pry(main)> require 'uri'
=> true
[3] pry(main)> URI.encode('{"email":"name@gmail.com"}')
=> "%7B%22email%22:%22name@gmail.com%22%7D"
答案 1 :(得分:1)
使用 CGI.escape ,而不是URI.encode / escape。 URI.encode不会转义JSON数组的括号。
emails = '{"list_1":[{"Jim":"jim@gmail.com"},{"Joe":"joe@gmail.com"}]}'
> URI::encode(emails)
=> "%7B%22list_1%22:[%7B%22Jim%22:%22jim@gmail.com%22%7D,%7B%22Joe%22:%22joe@gmail.com%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