4

How I convert this json var

email = {"email":"name@gmail.com"}

into this encoded string?

%7B%22email%22%3A%22name%40gmail.com%22%7D
Jack Zerby
  • 135
  • 2
  • 8

2 Answers2

3

Sure you can use the uri library shown here

[2] pry(main)> require 'uri'
=> true
[3] pry(main)> URI.encode('{"email":"name@gmail.com"}')
=> "%7B%22email%22:%22name@gmail.com%22%7D"
Anthony
  • 15,435
  • 4
  • 39
  • 69
  • This won't work with JSON arrays. See [my answer](https://stackoverflow.com/a/55382212/165673) – Yarin Mar 27 '19 at 16:32
1

Use CGI.escape, NOT URI.encode/escape. URI.encode will not escape the brackets of JSON arrays.

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

Yarin
  • 173,523
  • 149
  • 402
  • 512