简体   繁体   中英

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 \< 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 " :

> '[{"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 ( "'"</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\u003c/code> with \\\\u\u003c/code> . If you don't, JSON parser receives already decoded Unicode, which created polluted JSON.

It's not because of \<, rather the " 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: \\" .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM