Escape links in json using ruby - ruby-on-rails

I have a JSON object and 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.

Related

How to use gsub with array element in ruby

I am trying to remove some speicial character from array but it showing error
undefined method gsub! for array
def get_names
Company.find(#company_id).asset_types.pluck(:name).reject(&:nil?).gsub!(/([^,-_]/, '').map(&:downcase)
end
As it was said arrays don't respond to gsub!. An array is a collection of items that you might process. To achieve what you want you should call gsub on each item. Notice the difference between gsub! and gsub methods. gsub! will modify a string itself and might return nil whereas gsub will just return a modified version of a string. In your case, I'd use gsub. Also, reject(&:nil?) might be replaced with compact, it does the same thing. And you can call downcase inside the same block where you call gsub.
asset_types = Company.find(#company_id).asset_types.pluck(:name).compact
asset_types.map do |asset_type|
asset_type.gsub(/([\^,-_])/, '').downcase
end
UDP
Your regexp /([^,-_])/ means replace all characters that are not ,, - or _. See the documentation
If the first character of a character class is a caret (^) the class is inverted: it matches any character except those named.
To make it work as expected you should escape ^. So the regexp will be /([\^,-_])/.
There is a website where you can play with Ruby's regular expressions.
To put it simply without getting into other potential issues with your code, you are getting the error because gsub is only a valid Method in Class: String. You are attempting to use it in Class: Array.
If you want to use gsub on your individual array elements, you must do 2 things:
Convert your individual array elements to strings (if they aren't strings already).
Use gsub on those individual strings
The above can be done any number of ways but those basics should directly address your core question.
For what its worth, I would typically use something like this:
new_array = old_array.map {|element| element.to_s.gsub(*args)}
In fact, you could simply change the last section of your existing code from:
....gsub(*args).map(&:downcase)
to:
....map {|x| x.to_s.gsub(*args).downcase}

Escape quote in Dart Regex

I'm trying to use the regex /^[a-zA-Z0-9_$&+:;=?##|'<>.^*()%!-]+$/ with dart regex. I've seen you can use raw strings. So Ive put the above in between r'' like this:
r'^[a-zA-Z0-9_$&+:;=?##|'<>.^*()%!-]+$' but the ' is messing it up. How do I tell dart this is a special character..
EDIT
I tried this but it doesn't seem to work
static final RegExp _usernameRegExp = RegExp(
r"^[a-zA-Z0-9_$&+:;=?##|'<>.^*()%!-]+$",
);
So I have a TextField with a text controller for a username. A method like this
static bool isValidUsername(String username) {
return (_usernameRegExp.hasMatch(username));
}
I pass the controller.text as the username.
I've a function:
bool get isUserNameValid => (Validators.isValidUsername(userNameTextController.text.trim()));
I can type all the given characters in to the textbook but not '
Your RegExp source contains ', so you can't use that as string delimiter without allowing escapes. It also contains $ so you want to avoid allowing escapes.
You can use " as delimiter instead, so a raw string like r"...".
However, Dart also has "multi-line strings" which are delimited by """ or '''. They can, but do not have to, contain newlines. You can use those for strings containing both ' and ". That allows r'''...'''.
And you can obviously also use escapes for all characters that mean something in a string literal.
So, for your code, that would be one of:
r'''^[\w&+:;=?##|'<>.^*()%!-]+$'''
r"^[\w&+:;=?##|'<>.^*()%!-]+$"
'^[\\w&+:;=?##|\'<>.^*()%!-]+\$'
(I changed A-Za-z0-9$_ to \w, because that's precisely what \w means).
In practice, I'll always use a raw string for regexps. It's far too easy, and far too dangerous, to forget to escape a backslash, so use one of the first two options.
I'd probably escape the - too, making it [....\-] instead of relying on the position to make it non-significant in the character class. It's a fragile design that breaks if yo add one more character at the end of the character class, instead of adding it before the -. It's less fragile if you escape the -.

How to remove ANSI codes from a string?

I am working on string manipulation using LUA and having trouble with the following problem.
Using this as an example of the original data I am given -
"[0;1;36m(Web): You say, "Text here."[0;37m"
I want to keep the string intact except for removing the ANSI codes.
I have been pointed toward using gsub with the LUA pattern matching but I cannot seem to get the pattern correct. I am also unsure how to reference exactly the escape character sent.
text:gsub("[\27\[([\d\;]+)m]", "")
or
text:gsub("%x%[[%d+;+]m", "")
If successful, all I want to be left with, using the above example, would be:
(Web): You say, "Text here."
Your string example is missing the escape character, ASCII 27.
Here's one way:
s = '\x1b[0;1;36m(Web): You say, "Text here."\x1b[0;37m'
s = s:gsub('\x1b%[%d+;%d+;%d+;%d+;%d+m','')
:gsub('\x1b%[%d+;%d+;%d+;%d+m','')
:gsub('\x1b%[%d+;%d+;%d+m','')
:gsub('\x1b%[%d+;%d+m','')
:gsub('\x1b%[%d+m','')
print(s)

Swift: escape characters appear in json string

I'm constructing a JSON string by concatenating strings. To get the quotes correct for the web service (no quotes around numbers), I'm using escape characters. When I print the resulting string in Xcode, it looks fine.
{"number":999,"name":"new"}
But when I use Wireshark to capture what's going over the wire, I can see the escape characters in the string.
"{\"number\":999,\"name\":\"new\"}"
Here's the code that creates the string:
let jsonString:String = "{\"number\":" + num + ",\"name\":\"" + name + "\"}"
How can I create the string so the escape characters aren't there?
Thanks
The reason I couldn't send the JSON as a dictionary is that Swift dictionaries are unordered. In this case, the server is using MongoDB. I fixed the issue server side instead of trying to hack around it in the client.
Here's the reason: "Why does it happen: MongoDB uses a binary data format called BSON. In BSON, the order of keys always matters. Notice, in JSON an object is an unordered set of key/value pairs."
http://devblog.me/wtf-mongo
I'm fairly certain that the escape characters are being inserted by Wireshark in it's own output.

URL Escape in Uppercase

I have a requirement to escape a string with url information but also some special characters such as '<'.
Using cl_http_utility=>escape_url this translates to '%3c'. However due to our backend webserver, it is unable to recognize this as special character and takes the value literally. What it does recognize as special character is '%3C' (C is upper case). Also if one checks http://www.w3schools.com/tags/ref_urlencode.asp it shows the value with all caps as the proper encoding.
I guess my question is is there an alternative to cl_http_utility=>escape_url that does essentially the same thing except outputs the value in upper case?
Thanks.
Use the string function.
l_escaped = escape( val = l_unescaped
format = cl_abap_format=>e_url ).
Other possible formats are e_url_full, e_uri, e_uri_full, and a bunch of xml/json stuff too. The string function escape is documented pretty well, demo programs and all.

Resources