So am creating this quiz game. I have an ejs file on a route, where i collect questions and answers with the input element, and on click at the submit button, an array is created, containing many objects, one for each question and for its answers. and then this array is set to be the value of the submit button, that is wrapped in a form that will get you to /created with a post method. Then i want to use the array in server.js, where i am handling routes; am doing it with req.body.name, which is the name of the submit button. The thing is, i was getting this : [ '[object Object],[object Object]' ] So after searching, i discovered that in the first place, to append the objects to the array, in the ejs file, i should be using array.push(JSON.stringify(obj)). I did that, and this is what i received:
[
'{"question":"question1","answers":[{"text":"asnwer1","correct":true},{"text":"asnwer2","correct":false}]},{"question":"question2","answers":[{"text":"asnwer3","correct":true},{"text":"asnwer4","correct":false}]}'
]
And this is not what i want to get, i want to have an array with two seperate js objects, not json, and i dont want the whole thing to be weapper with ' '. I want it to be:
[
{question:"question1",
answers:
[{text:"asnwer1",correct:true},
{text:"asnwer2",correct:false}
]},
{question:"question2",
answers:[
{text:"asnwer3",correct:true},
{text:"asnwer4",correct:false}
]}
]
so in the server.js where i am handling routes, i used : let bla = JSON.parse(req.body.name) But i get:
SyntaxError: Unexpected token , in JSON at position 105
I think there is many mistakes that am doing, so please help...
JSON.parse() parses JSON object and convert it to javascript object. You have string of collection of objects seperated by comma that's why JSON.parse is throwing an error. It can only parse JSON objects not comma. So you have to remove those comma split it into objects and then parse it.
Demo Solution will be below for splitting and then parsing the each object and updating it in an array
let array = [
'{"question":"question1","answers":[{"text":"asnwer1","correct":true},{"text":"asnwer2","correct":false}]},{"question":"question2","answers":[{"text":"asnwer3","correct":true},{"text":"asnwer4","correct":false}]}'
]
var arrayAfterSplit = array[0].split(',{"question"')
for(let i = 0;i<arrayAfterSplit.length;i++)
{
if(i > 0)
{
arrayAfterSplit[i] = '{"question"'+arrayAfterSplit[i];
}
arrayAfterSplit[i] = JSON.parse(arrayAfterSplit[i])
// console.log(arrayAfterSplit[i])
}
console.log(arrayAfterSplit)