序列化:将数据结构反序列化到JSON或从JSON反序列化

我是Javascrit / JQuery的新手。

我有一个测验程序的数据结构,如下所示:

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

测验由一定数量的此类问题组成,我想将每个问题的数据存储在内存中或作为JSON对象发送到数据库。

我怀疑我会使用var questionList = new Array(); 每个项目都是JSON。

如何序列化/反序列化给定问题? 如何初始化新的问题结构?

实现这一目标的最佳做法是什么?

您可以在浏览器中使用内置JSON对象,除非您想支持旧的IE版本,请查看此链接: 将数组转换为JSON 。

您不需要在序列化的JSON-String中发送单个问题,也可以将整个问题数组或其中的一部分与数据库同步。 在你的情况下试试这个。

 // 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); } 

你会得到这样的输出

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

可以在下面找到有关内置JSON对象的更多信息

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

在此示例中,不需要JQuery.parseJSON()。 当然,如果你愿意,你可以使用JQuery。 有关JQuery.parseJSON()的更多信息,请访问https://api.jquery.com/jQuery.parseJSON/ 。 我没有看到在你的情况下使用JQuery.parseJSON()的必要性。