Escape links in json using ruby
I have a JSON object and 开发者_Python百科I want to convert it escaping / characters.
Object:
{
"id":"123",
"name":"test",
"link":"https://google.com"
}
Desired result:
{
"id":"123",
"name":"test",
"link":"https:\/\/google.com"
}
How can I do this transformation in Ruby, RoR?
If it is at all possible, modify the values before they are JSON'd. In activerecord, I believe you can change the value and convert it to JSON - so long as you don't save the model, that change will be discarded.
In ruby, JSON is just a string, so you could do
my_json.gsub('/', '\\/')
This would convert any forward slashes in the keys, too. I don't know of any reason a JSON string would contain forward slashes outside of a string, so that should be fine.
If you want to avoid converting the keys, you could use a (slightly complicated) regular expression:
my_json.gsub(/:\s*"[^"]*\/[^"]*"/) { |m| m.gsub('/', '\\/') }
This finds a section that starts with a colon, possibly some whitespace after that, then some double quotes. It then looks for some optional stuff (anything that isn't a double quote), then a forward slash, them more stuff that isn't a double quote, then an actual double quote. So essentially, the minimum it will find is :"/"
- it then passes each matching string into the block, and runs the previous gsub to convert the slashes. The output of the block then replaces whatever was found in the initial gsub.
I'm sure there are neater ways, so play around.
精彩评论