I'm trying to make a quiz with HTML, CSS and JavaScript. Now i'm trying to see if the jsonData works but i get this error message but i can't find where the unecpected character is (it says line 1 column 2) but don't see it Other thing am i doing it good? I just started this year with coding
var jsonData = [
{
"q1": {
"question": "what is the Capital city of Australia ",
"answers": {
"a": "Melbourne",
"b": "Sydney",
"c": "Caneberra",
"d": "Brisbane"
},
"correctAnswers": "c"
}
},
]
const me = JSON.parse(jsonData)
console.log(me.correctAnswers);
The problems have already been pointed out in the comments by T.J Crowder and Samball, but I wanted to show you the difference between a JavaScript data structure and a JSON string that needs to be parsed so you can better understand their comments.
Here a small program to illustrate what I've just written.
// this needs to be parsed so you can access it as JS data structures
const stringData = `[
{
"q1": {
"question": "what is the Capital city of Australia ",
"answers": {
"a": "Melbourne",
"b": "Sydney",
"c": "Caneberra",
"d": "Brisbane"
},
"correctAnswers": "c"
}
}
]`;
// no need for this to be parsed, as it already is a JS data strucure (an array in this case)
const alreadyJavaScript = [
{
"q1": {
"question": "what is the Capital city of Australia ",
"answers": {
"a": "Melbourne",
"b": "Sydney",
"c": "Caneberra",
"d": "Brisbane"
},
"correctAnswers": "c"
}
}, // In JavaScript this comma is fine, in JSON it is not!
]
// parse string
const me = JSON.parse(stringData)
// now print both to see that they are in fact identical
// Keep in mind it's an array not an object!
console.log(me[0]);
console.log(alreadyJavaScript[0])
Note: While it is perfectly fine to put a
,at the end of the last element in JavaScript, JSON does not allow that!