C#, How to unescape characters in JObject values? - javascript

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.

Related

Why can't Javascript parse this JSON array from a string literal?

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\"}]

Javascript .replace() of the character " with the characters \"

I am trying to pass a JSON string to a C# .exe as a command line argument, from Javascript as a node.js child-process. For the sake of argument my JSON looks something like this:
string jsonString = '{"name":"Tim"}'
The issue with passing this as a C# arg is that the double quotation marks must be retained if I hope to parse it in the C# code. As such, what I need to pass into the C# command line needs to look something like this, where I escape the double quotation mark:
string jsonStringEscaped = '{\"name\":\"Tim\"}'
The motivation for doing this is that it allows me to maintain a consistent object structure across the two languages, which is obviously highly desirable for me.
In order to achieve this, I am attempting to use the Javascript .replace() method prior to sending the argument to the C#, and to do this I use a simple RegEx:
string jsonStringEscaped = jsonString.replace(/\"/g,"\\\"")
Unfortunately, this returns something of the form '{\\"name\\":\\"Tim\\"}' which is useless to me.
I have tried variations on this:
string jsonStringEscaped = jsonString.replace(/\"/g,"\\ \"")
\\ returns '{\\ "name\\ ":\\ "Tim\\ "}'
string jsonStringEscaped = jsonString.replace(/\"/g,"\\\\")
\\ returns '{\\\\name\\\\:\\\\Tim\\\\}'
string jsonStringEscaped = jsonString.replace(/\"/g,"\\\")
\\ is invalid
string jsonStringEscaped = jsonString.replace(/\"/g,"\\\ ")
\\ returns '{\\ name\\ :\\ Tim\\ }'
I have tried variations where the second .replace() argument is contained within single quotation marks '' rather than double quotation marks "" with no success.
Can anyone tell me what I am doing wrong? Better yet, can anyone suggest a more efficient method for doing what I am trying to achieve?
Unless I'm misreading you, I think you're just trying to escape a character that doesn't need to be escaped in your regex (").
var jsonString = '{"name":"Tim"}'
var escaped = jsonString.replace(/"/g, '\\"');
// escaped == "{\"name\":\"Tim\"}"

How to deserialize Json object which contain control character using Dojo.fromJson

I am using Dojo.fromJson to convert json string to javascript object, but throw exception. Because, there are control characters such as ',\n,\r in the json string.
How can I solve this problem in dojo? convert json string to javascript object, even if there are control characters.
I use Newtonsoft.JsonConvert.SerializeObject to convert C# oject to json data. Json Object: {"name":"'\"abc\n123\r"} then, I use Dojo.fromJson(' {"name":"'\"abc\n123\r"}') to convert json data to javascript object.
Thank you very much!
Problem, i believe is the double-quote which should be escaped by triple backslashes. You can use "native browser JSON decode" as searchterm for "dojo fromJson" synonym.
Without knowing my way around C# - I havent tested but i believe following should work:
string c_sharp_name = "'\"abc\n123\r";
// C#Object.name
c_sharp_name = c_sharp_name.
replace('"', '\\"'). // maybe add a slash on serverside
replace('\n', '\\\n').
replace('\r', '\\\r');
since
while this fails:
{"name":"'\"abc\n123\r"} // your single backslash
this would work:
{"name":"'\\\"abc\\\n123\\\r"} // working triple backslash escape

How to parse Json with jquery having special chars in it?

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.

How do I escape backslashes in JSON?

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/

Categories