I handle passed data in ejs like this: It works fine.
let parsed_json = JSON.parse('<%-JSON.stringify(passed_data)%>');
But how can I pass a string variable as the passed_data name inside this string? The following doesn't work. The output is just " + passed_data + "
let name_of_variable = 'passed_data';
let parsed_json = JSON.parse('<%-JSON.stringify(' + name_of_variable + ')%>');
console.log(parsed_json);
---
+ passed_data +
Also I have another question to passed json when I am at it. It seems strange that I have to stringify the passed json object, and then parse it again. But if I just want to used the passed json Object I only get this.
[object Object]
Is this the intended way?
You can try using Template literals like below:
let name_of_variable = 'passed_data';
let parsed_json = `<%-${JSON.stringify(name_of_variable)}%>`;
console.log(parsed_json);
But, why are you stringifying name_of_variable since its value is a string and you can't JSON.parse ejs syntax? It will be helpful you can explain in more detail what you want to achieve exactly. Thank you.
Yeah, if you try to typecast (or convert an object to string), it will show like [object Object]. Try the following in the console. That's why we normally use JSON.stringify() to change an object or JSON data to string form and JSON.parse() to get back object or JSON format from stringified data.
console.log({a:'1'} + '')