I am using Firefox's native JSON.parse() to parse some JSON strings that include regular expressions as values, for example:
var test = JSON.parse('{"regex":"/\\d+/"}');
The '\d' in the above throws an exception with JSON.parse(), but works fine when I use eval (which is what I'm trying to avoid).
What I want is to preserve the '\' in the regex - is there some other JSON-friendly way to escape it?
You need to escape the escape backslashes already in there :) like this:
var test = JSON.parse('{"regex":"/\\\\d+/"}');
You can test it a bit here: http://jsfiddle.net/h3rzE/
Related
I have some Javascript code embedded in some JSON fields.
For example:
{
"elements": [{
"bindingParams": "return field.innerHTML.match(/\\d+/gi).toString();\n"
}]
}
And I want to write this code to a new file. The thing is that when this Javascript is set as a value to a JObject the newlines and other characters as the backslash are being escaped.
I have tried using Regex.Unescape(field.Value<string>()), but I get an error in fields with \\d
The error is parsing 'field.innerHTML.match(/\\d+/gi).toString();' - Unrecognized escape sequence \\d.
I could always go with field.Value<string>().Replace("\\n", "\n).Replace("\\","\").Etc(...) but I don't know the sequences that Newtonsoft JObject is escaping.
I would like to know the escape characters that Newtonsoft uses or a method/function from Newtosoft that allows me to unescape the string.
I appreciate your help. Thanks in advance.
The double backslash "\\d" is causing the problem.
Before parsing the jsonString try to replace them this way:
var jsonString ="{\"elements\": [{\"bindingParams\": \"return field.innerHTML.match(/\\d+/gi).toString();\n\"}]}";
jsonString = jsonString .Replace("\\", "\\\\"); // <=== this line
var o = JObject.Parse(jsonString); // This works !
I found out that the issue was that I was trying to unescape an already unescaped string.
The field.Value<string>() already unescapes the string. So the solution to my issue was just not to call Regex.Unescapeand use the value directly.
Sorry.
What I am trying to do is simple. Parse this array holding json objects into a Javascript array.
var merchantsJson = JSON.parse('[{"id":61693,"name":"Más"},{"id":61690,"name":"\u0027\u0022\u003C/div\u003E"}]');
But the unicode character \u003C seems to be breaking the parser. In the chrome console I see "Uncaught SyntaxError: Unexpected token <"
A little more info. The above is what the code is evaluated to. In reality the code contains a jsp expression.
var merchantsJson = JSON.parse('${jsonArr}');
If I remove the single quotes, there is no issue, but eclipse give me an "missing semicolon" error message. Is it possible to parse the array with the quotes as I am trying to do?
The interpolation of ${jsonArr} is already a JavaScript object. When you wrap it in '${jsonArr}' this turns it into a string and you have to use JSON.parse.
There's no need to make it a string. You can just do var merchantsArray = ${jsonArr}. JSON constructs are already interoperable with JavaScript code.
Because there's an extra " in your string literal that is encoded by \u0022:
> '[{"id":61693,"name":"Más"},{"id":61690,"name":"\u0027\u0022\u003C/div\u003E"}]'
[{"id":61693,"name":"Más"},{"id":61690,"name":"'"</div>"}]
In short, your JSON in the string is invalid. You would need to escape the unicode escape sequences for the quotes in the string literal ("'\u0022</div>"), by using
JSON.parse('[{"id":61693,"name":"Más"},{"id":61690,"name":"\u0027\\u0022\u003C/div\u003E"}]'
// ^
or escape the quote character ("'\"</div>"):
JSON.parse('[{"id":61693,"name":"Más"},{"id":61690,"name":"\u0027\\\u0022\u003C/div\u003E"}]');
// ^^
However, there actually is no need to use JSON at all. Just output a JS array literal into your code:
var merchantsJson = ${jsonArr};
Try to replace \u with \\u. If you don't, JSON parser receives already decoded Unicode, which created polluted JSON.
It's not because of \u003C, rather the \u0022 character is causing the issue, since it's a quotation mark and JavaScript treats it literally ending the string.
You need to escape that character: \\u0022 .
you have to use special character in your JSON string, you can escape it using \ character.
you need to replace \ with \\.
[{\"id\":61693,\"name\":\"Más\"},{\"id\":61690,\"name\":\"\\u0027\\u0022\\u003C/div\\u003E\"}]
Is there any method to find out if the given string is HTML Escaped or not?
Consider the following javascript code:
<script>
var str="hello";
var str_esc=escape(str);
document.write(isHTMLEscaped(str)) // *Should print False*
document.write(isHTMLEscaped(str_esc)); // *Should print True*
</script>
Is there any method equivalent to isHTMLEscaped in the above case?
I found that using
escape(unescape(str))
will always provide an escaped string. And the unescape string will do nothing unless the string itself contains escaped expressions.
Note: should have used encodeURI(decodeURI(str)) instead as escape is now depreciated.
As "hello"==escape("hello"), no, you can't at all guess if escaping was applied.
If you want to know if it's probable that the string has been escaped, then you might test
var wasProbablyEscaped = /%\d\d/.test(str);
var wasProbablyNotEscaped = !wasProbablyEscaped && /%\d\d/.test(escape(str));
as escaping adds % followed by two digits when something has to be escaped. But you can't be totally sure as some strings don't change when you escape them.
In your case, I'd probably advise you not to escape if wasProbablyEscaped is true.
I got a json structure somehow as below and my question is how can i parse this with jQuery so that i can use it like myJson[0].name and than alert it so that "M\\xe9t\\xe9o" = Météo.
Jquery tells me this is invalid json why ?
Json uses double backslash if i use single backslash ("M\xe9t\xe9o") Jquery is OK with the syntax.
var jsonObj = '{"title":[{"id":"1","name": "M\\xe9t\\xe9o"},{"id":"2","name": "Meteo"}]}';
var myJson = jQuery.parseJSON(jsonObj);
The JSON syntax only allows \uxxxx escapes.
Change it to "M\\u00e9t\\u00e9o".
If you use a single backslash, it gets parsed by the Javascript string literal, so the actual string value contains the real Unicode character, not an escape. In other words, "M\xe9t\xe9o" === "Météo"
It is looks like the json was incorrectly (manually?) encoded. When you encode it in UTF-8, e.g. with PHP, you'll get:
{"title":[{"id":"1","name": "M\u00e9t\u00e9o"},{"id":"2","name": "Meteo"}]}
which is correctly parsed by JS. But \xe9 is unrecognized by parser.
I am having problems when trying to use a rails variable within javascript code.
For example, I might define a link_to_remote, with parameter
:complete => "alert('my_var');"
If my_var = "I'm testing.", then the javascript code will break due to the single quote closing the code prematurely. If I try using escape_javascript(my_var) so that the quote gets turned into \', it doesn't seem to fix the problem.
I've noticed that when you try alert('I\'m testing'); there's a problem, but if you do alert('I\\'m testing'), it works. Since escape_javascript only turns ' into \', rather than \\', does somebody have a suggestion for how to handle this?
Thanks!
Eric
when you try alert('I\'m testing'); there's a problem
Backslash is also an escape in Ruby strings! So the string literal:
"alert('I\'m testing');"
means the string:
alert('I'm testing');
the backslash is gone already before JavaScript gets a look at it. When you are writing a JavaScript string literal inside a Ruby string literal you need to escape the escape, \\, to get a real \ that will then, in JavaScript, escape the apostrophe.
escape_javascript correctly generates the backslash for JavaScript, if a backslash was included in its input. But again, if you're writing a string literal, you have to escape the backslash to get a real backslash:
escape_javascript("\b") -> this is a backspace character!
escape_javascript("\\b") -> this is backslash-then-letter-b;
escaped for JavaScript literal to double-backslash-then-b.
So, this is fine:
"'"+escape_javascript(myvar)+"'"
alternatively, you can use a JSON encoder to create the JavaScript string literal including the surrounding quotes.