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

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

Related

C#, How to unescape characters in JObject values?

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.

Is there any difference in JSON Key when using single quote and double quote?

I ran two pieces of javascript codes in a online JS running platform:Website Link
pets = '{'pet_names':[{"name":"jack"},{"name":"john"},{"name":"joe"}]}';
var arr = JSON.parse(pets);
alert(arr.pet_names[1].name);
Code with double quotes ("pet_names") would be OK but with single quotes('pet_names') would remind a error:"Unexpected identifier"
pets = '{"pet_names":[{"name":"jack"},{"name":"john"},{"name":"joe"}]}';
var arr = JSON.parse(pets);
alert(arr.pet_names[1].name);
So, why do it would happen?
In JSON only double quotes are valid.
You can find the standard on JSON.org
A value can be a string in double quotes, or a number, or true or
false or null, or an object or an array. These structures can be
nested.
In other words, no strings in single quotes.
The first one didn't work because you have a syntax error where you try to define your string literal
you probably wanted
pets = '{\'pet_names\':[{"name":"jack"},{"name":"john"},{"name":"joe"}]}';
notice the quotes are escaped.
Now if you used that string in the json parser you would still get an error(SyntaxError: Unexpected token ') because keys in JSON must be defined with double quotes, using single quotes is valid for defining JavaScript object literals which is separate from JSON.

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.

Json String with comment out quotes in variable

I have a JSON string hardcoded in my Javascript.
valiJsonString = '{"ssss","ddddddddd\"ddd"}';
The DOM says -> {"ssss","ddddddddd"ddd"}
Can someone tell me why javascript replace my \" into " ?
// try to parse
valiJsonString secureEvalJSON (valiJsonString) //<-- error: jsonString is not valid
working example
"The DOM says" doesn't make much sense, as the DOM doesn't say anything. Do you mean the object browser in Firebug (or some other development console)?
Now, inside a string, \" is the quote character. You have to compensate for this escaping since you do not want it, but instead a verbatim slash.
So perhaps you want \\ followed by ", which is the slashed character followed by the quote character.
In addition, the given JSON looks like it ought to represent an array not an object, since you have no keys:
var str = '["ssss","ddddddddd\\"ddd"]';
The actual value of this JSON-format string inside your browser is now:
["ssss","ddddddddd\"ddd"]
\ is an escape character. try \\
If you want your string to come through escaped, then you need to escape your escape character:
valiJsonString = '{"ssss","ddddddddd\\"ddd"}';
I've added second \ (\ is escape char) and fixed lack of = and type of table {} vs []
http://jsfiddle.net/4wVaR/9/

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