<div>
var arrayContent='<%= myJsonArray %>'
<!--myJsonArray is sent to this ejs file using the render function in
index.js while rendering this ejs file -->
</div>
<script>
var index=0;
function myfunc(){
console.log(arrayContent); /*[object Object],[object Object],[object
Object],[object Object] */
var arrContentJson= JSON.parse(arrayContent);
console.log(arrContentJson[index]); /* Uncaught SyntaxError: Unexpected
token o in JSON at position 1 */
}
</script>
Why am I not able to access the content of the parsed Json array (arrContentJson). How can I access it ?
myJsonArrayis probably an array, not JSON representing an array. (You also have<div>tags here instead of<script>.) It isn’t safe to put arbitrary JSON directly in<script>tags, though; you need to use escaping specifically designed for that purpose. (If you implement that, you should test that it’s working by making sure<is escaped as\x3c.)console.loglogs you provided are not correct. InitiallyarrayContentis a string. How does it look like? The error you get should happen at the line withJSON.parse()JSON.parse(). If you're passing JSON via an EJS template, it should load in that script as an object literal, not a string. Just remove the quotes around<%= myJsonArray %><div>.