Search code examples
javascriptnode.jsjsonparsingejs

JSON.parse not parsing string of array of object


In my Node.js file route I am rendering an ejs file with variables passed as stringified array of object -

let scriptArray = [
  {
    charValue: 'a',
    encodedValueMain: 'g',
  },
  {
    charValue: 'b',
    encodedValueMain: 'o',
  },
  ]


router.route('/playground')
.get((req, res) =>{
    res.render('playground', {value: JSON.stringify(scriptArray)})
})

where scriptArray is a JSON object

Then, I embedded the value in a hidden input tag in the playground.ejs file -

<input type="hidden" id="test" value="<%= value %>">

and I tried to parse it in the JS script of this ejs file for further use -

(function () {
    let temp = document.getElementById('test');
    let script = JSON.parse(temp);
    console.log(script)
  })();

I was expecting the output to be an array of objects, exactly like how I assigned it in node.js file. but rather it gives me an error in the browser console -

VM600:1 Uncaught 
SyntaxError: Unexpected token 'o', "[object HTM"... is not valid JSON
    at JSON.parse (<anonymous>)
    at playground.js:5:19
    at playground.js:7:5
(anonymous) @   playground.js:5
(anonymous) @   playground.js:7

please help me solve this issue. Is there any other way I can access the node.js passed variables in my frontend JS file, without embedding it in a hidden input tag? If not, how do I solve this issue?? Thanks in advance.


Solution

  • That's because you are passing an HTML-Element to the JSON.parse function.

    Fix:

    (function () {
        let temp = document.getElementById('test');
        let script = JSON.parse(temp.value); // <-- changed line
        console.log(script)
      })();
    

    Also keep in mind that JSON has " as delimiters, so your value in

    <input type="hidden" id="test" value="<%= value %>">
    

    must be escaped for HTML. That might already be the case - depending on what you use to render...