safe JSON parsing. How JSON parse can parse UTF characters? - javascript

Hello I am wondering why this line doesn't work:
JSON.parse({"a":"\u00A9"})
I tried to serach in MDN website but I didn't find anything referring to in json.parse
Unicode escaping is syntactically legal in js according to this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#String_literals
What is the problem and how can I safely parse text with JSON.parse

{"a":"\u00A9"} is a JavaScript object literal.
JSON.parse expects to be passed a string so it is implicitly converted to a string ("[object Object]").
The [ is fine, because a JSON text can start with an array.
The o is then an error because it isn't allowed there.
A literal copyright symbol (remember that \u00A9 inside a JavaScript string literal will be consumed by the JS parser before it gets to the JSON parser) or the unicode escape sequence would be fine.
console.log(JSON.parse('{"a":"\u00A9"}'));
console.log(JSON.parse('{"a":"\\u00A9"}'));
Note that creating a string literal in JS source code that contains JSON and then parsing it is a terrible idea. You have to deal with nested levels of escaping, and it is inefficient.
If you have an object: use the object.
var data = {"a":"\u00A9"};
console.log(data.a);

Related

Unexpected Token in string version of valid JSON while performing JSON.parse

I am having problem converting a JSON String into Javascript object.
I ran into a few suggestions which said that I should not be using multi-line string but using single line string too did not work.
Snippet: https://jsfiddle.net/ankschoubey/hjh2d3z6/
SyntaxError: Unexpected token F in JSON at position 4536
Because you're including JSON as a JavaScript string value, you'll have to double-up on all the embedded backslash characters because they'll be parsed twice: first when the JavaScript parser reads the overall string constant to create the string value, and then again when you call JSON.parse().
Thus that portion of the string with \" should be \\". That way, the JavaScript string parsing will turn \\" into just \", and that's what will make the JSON parser happy.

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

JSON Lint says it's valid but JSON.parse throws error

I have simple JSON that I need to parse to object. Strangely it doesn't work even though if I copy and paste my JSON string to JSONLint (http://jsonlint.com/) it will show that it's valid.
var string = '{"token":"9eebcdc435686459c0e0faac854997f3","email":"201403050007950","id":"13","updated_at":"2014-03-05 10:34:51","messageguides":"[{\"name\":\"Un-named Messaging Guide 1\",\"pages\":[\"sustainabilitydirectors\",\"marketingnbusinessdevelopmentdirectors\"],\"date\":1394015692958}]"}';
var obj = JSON.parse(string); // Unexpected token n
console.log(obj);
The \ characters in the data are treated as JSON escape characters when you parse the raw JSON.
When you embed that JSON inside a JavaScript string, they are treated as JavaScript escape characters and not JSON escape characters.
You need to escape them as \\ when you express your JSON as a JavaScript string.
That said, you are usually better off just dropping the JSON in to the JavaScript as an object (or array) literal instead of embedding it in a string and then parsing it as a separate step.
var obj = {"token":"9eebcdc435686459c0e0faac854997f3","email":"201403050007950","id":"13","updated_at":"2014-03-05 10:34:51","messageguides":"[{\"name\":\"Un-named Messaging Guide 1\",\"pages\":[\"sustainabilitydirectors\",\"marketingnbusinessdevelopmentdirectors\"],\"date\":1394015692958}]"};

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.

Categories