Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 212
mad_fox Avatar asked Jun 30 '15 14:06

mad_fox


People also ask

How do I parse a JSON array in JavaScript?

To parse a JSON Array in JavaScript, pass the JSON Array string to the JSON.parse () method. This method parses the string and returns a JavaScript equivalent. If the JSON String is invalid, it will throw a SyntaxError. Use the JSON.parse () method to parse a JSON Array into a JavaScript equivalent.

What is an array literal in JavaScript?

An array inside a JSON string is known as an array literal. It is the same as arrays in JavaScript however it can only contain numbers, strings, booleans, arrays, objects, and null values except functions, expressions, dates, and undefined like arrays. JavaScript permits you to create a JSON string from an array.

What is the difference between JSON and JavaScript object literals?

The main difference between a JSON object and a regular JavaScript object – also called an object literal – comes down to the quotation marks. All the keys and string type values in a JSON object have to be wrapped in double quotation marks ( " ). JavaScript object literals are a bit more flexible.

What is a @JSON array?

JSON arrays work pretty much the same way as arrays in JavaScript, and can contain strings, booleans, numbers, and other JSON objects. For example: Here's what that might look like in plain JavaScript:


1 Answers

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.

like image 185
Explosion Pills Avatar answered Sep 19 '22 21:09

Explosion Pills