Ivan Ivan - 23 days ago 10
Javascript Question

how to make my json valid

I've got an array:

var myArray = [
{question: "Who is Prime Minister of the United Kingdom?",
choices: ["David Cameron", "Gordon Brown", "Winston Churchill", "Tony Blair"],
correctAnswer:0},
{question: "What is the capital of UK?",
choices: ["Paris", "Washington", "London", "Liverpool"],
correctAnswer:2}];


After I stringified it. It looked like this:

JSON.stringify(myArray)
"[
{
"question":"Who is Prime Minister of the United Kingdom?",
"choices":[
"David Cameron","Gordon Brown",
"Winston Churchill",
"Tony Blair"
],
"correctAnswer":0
},
{
"question":"What is the capital of UK?",
"choices":[
"Paris",
"Washington",
"London",
"Liverpool"
],
"correctAnswer":2
}
]"


Which is not valid JSON. How to make it valid?

Answer

Just remove the " characters from the two far ends.

Note, however, that they are not part of the output of JSON.stringify, they are added to the display by your developer console to indicate that the output is a string. This means you only need to remove them if you are copy/pasting the output from your console.