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?
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.
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.
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.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With