سؤال

I'm fairly new to Javascrit / JQuery.

I have a data structure for a quiz program like this:

qData = {
            qQuestionText: '', qAnswer1: ''
        , qAnswer2: '', qAnswer3: '', qAnswer4: '', qGoodAns: '', qAnswerText: ''};

A quiz is made of a certain number of such questions and I want to store each question's data in memory or send to a database as a JSON object.

I suspect I will use var questionList = new Array(); and each item will be a JSON.

How do I serialize / deserialize a given question? How do I initialize a new question structure?

What is best practice to achieve this?

هل كانت مفيدة؟

المحلول

You can use the build-in JSON Object in Browser, unless you want to support the old IE version take a look at this link: Convert array to JSON.

You don't need to send a single question in serialized JSON-String, you can also synchronize the whole question array or a part of it with your data base. Try this in your case.

// create question objects
var q1 = {question:"your question 1"};
var q2 = {question:"your question 2"};
// creat question array
var questionList = new Array();
// add question to List
questionList.push(q1);
questionList.push(q2);
var yourJsonString = JSON.stringify(questionList);
console.log("jsonstring of questions: " + yourJsonString);

var newList = JSON.parse(yourJsonString);
// loop through the parsed Array Object
for (var i in newList) {
   // use tmp to get the question object
   var tmp = newList[i];
   // do what ever you want
   console.log(tmp.question);
}

and you will get some output like this

jsonstring of questions: [{"question":"your question 1"},{"question":"your question 2"}]
your question 1
your question 2

more info to the build-in JSON Object can be found under

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

In this example, the JQuery.parseJSON() are not needed. Surely you can use JQuery, if you want to. more about JQuery.parseJSON() can be found unter https://api.jquery.com/jQuery.parseJSON/ . I don't see the necessity to use JQuery.parseJSON() in your case.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top