Home > Mobile >  How to pass values into JSON variable
How to pass values into JSON variable

Time:10-18

I am working on a form that will send data from the google forms to the real-time database. However, I am having a hard time setting the data in JSON format (fairly new to this).

I would like to format it like the following below (data there are examples):

"QuizName": {
    "1": {
        "question-type": "multiple-choice",
        "question": "Find the odd one out?",
        "option1": "FTP",
        "option2": "POP",
        "option3": "TCP",
        "answer": "POP",
        "date-added": "10/06/2021"
    },
    "2": {
        "question-type": "checkbox",
        "question": "Which of the following are not planets?",
        "option1": "Earth",
        "option2": "Sun",
        "option3": "Jupiter",
        "option4": "Mars",
        "option5": "Pluto",
        "answer": "Sun, Pluto",
        "date-added": "10/06/2021"
    }
    "3": {
        "question-type": "Input-text",
        "question": "In your own words, describe Mitosis?",
        "user-input": "Mitosis is a process where a single cell divides into 2 identical daughter cells",
        "answer": "user-input",
        "date-added": "10/06/2021"
    }
}

The code below is where I extract the form questions and answers which calls the sendExtractedData. From there, I would like to pass in the values (the parameters are arrays except for the form title parameter).

  function extractFormData(){
  var form = FormApp.getActiveForm();
  var form_title = DriveApp.getFileById(form.getId()).getName();
  var items = form.getItems();
  var number_of_questions = items.length;

  var question; 
  var answers;
  var answer;
  
  var item_type = [];
  var question_title = [];
  var questions = [];
  var correctanswer = [];

  for (var i = 0; i < items.length; i  ) {
    var item = items[i];
    switch(item.getType()) {
      case FormApp.ItemType.MULTIPLE_CHOICE:
        item_type.push(item.getType());
        question = item.asMultipleChoiceItem();
        answers = question.getChoices();
        question_title.push(question.getTitle());

        console.log("Question: "   question.getTitle());
        console.log("Number of answers: "   question.getChoices().length);
        for (var j = 0; j < answers.length; j  ) {
          answer = answers[j];
          questions.push(answer.getValue());
          correctanswer.push(answer.isCorrectAnswer());
          console.log(answer.getValue());
          console.log("Is correct answer? "   answer.isCorrectAnswer());
        }
        break;
      case FormApp.ItemType.CHECKBOX:
        item_type.push(item.getType());
        question = item.asCheckboxItem();
        answers = question.getChoices();
        question_title.push(question.getTitle());

        console.log("Question: "   question.getTitle());
        console.log("Number of answers: "   question.getChoices().length);
        for (var k = 0; k < answers.length; k  ) {
          answer = answers[k];
          questions.push(answer.getValue());
          correctanswer.push(answer.isCorrectAnswer());
          console.log(answer.getValue());
          console.log("Is correct answer? "   answer.isCorrectAnswer());
        }
        break;
      case FormApp.ItemType.PARAGRAPH_TEXT:
        item_type.push(item.getType());
        question = item.asParagraphTextItem();
        question_title.push(question.getTitle());
        console.log("Question: "   question.getTitle());
        break;
      case FormApp.ItemType.TEXT:
        item_type.push(item.getType());
        qustion = item.asTextItem();
        question_title.push(question.getTitle());
        console.log("Question: "   question.getTitle());
        break;
    }
  }

  var form_questions = unique(question_title);

  sendExtractedData(form_title, item_type.join(', '), form_questions.join(', '), questions.join(', '), correctanswer.join(', '));
}

 function sendExtractedData(form_title, typeofquestion, question, typeofanswers, correctanswer) {
 var quizDatabase = FirebaseApp.getDatabaseByUrl('URL REALTIME DATABASE');
 var newDate = new Date();
 var dateAdded = newDate.toLocaleString("en-US");
 var dataToExport = { };
 
 //quizDatabase.setData("nameofdatabase/"  form_title  "/", dataToExport);
}

Any help would be appreciated.

CodePudding user response:

function makejson() {
  let obj = {"Simple Questions":{"1":{"question-type":"multiple-choice","question":"What color is the highest intensity of light can comes into the atmosphere unrefracted?","option1":"red","option2":"green","option3":"blue","option4":"yellow","answer":"green","date-added":"10/11/21"}}};
  let json = JSON.stringify(obj);
  Logger.log(json);
  return json;
}

function changejson() {
  let json = makejson();
  Logger.log(json);
  let obj = JSON.parse(json);
  obj["Simple Questions"][1]["option1"] = "White";
  let json2 = JSON.stringify(obj);
  Logger.log(json2);
}

Try running changejson() and you getting the following execution log:

12:24:57 AM Notice  Execution started
12:24:56 AM Info    {"Simple Questions":{"1":{"question-type":"multiple-choice","question":"What color is the highest intensity of light can comes into the atmosphere unrefracted?","option1":"red","option2":"green","option3":"blue","option4":"yellow","answer":"green","date-added":"10/11/21"}}}
12:24:56 AM Info    {"Simple Questions":{"1":{"question-type":"multiple-choice","question":"What color is the highest intensity of light can comes into the atmosphere unrefracted?","option1":"red","option2":"green","option3":"blue","option4":"yellow","answer":"green","date-added":"10/11/21"}}}
12:24:56 AM Info    {"Simple Questions":{"1":{"question-type":"multiple-choice","question":"What color is the highest intensity of light can comes into the atmosphere unrefracted?","option1":"White","option2":"green","option3":"blue","option4":"yellow","answer":"green","date-added":"10/11/21"}}}
12:24:59 AM Notice  Execution completed

With a fixed version of provided JSON:

function makejson() {
  let obj = { "Quizname": { "1": { "question-type": "multiple-choice", "question": "Findtheoddoneout?", "option1": "FTP", "option2": "POP", "option3": "TCP", "answer": "POP", "date-added": "10/06/2021" }, "2": { "question-type": "checkbox", "question": "Whichofthefollowingarenotplanets?", "option1": "Earth", "option2": "Sun", "option3": "Jupiter", "option4": "Mars", "option5": "Pluto", "answer": "Sun,Pluto", "date-added": "10/06/2021" }, "3": { "question-type": "Input-text", "question": "Inyourownwords,describeMitosis?", "user-input": "Mitosisisaprocesswhereasinglecelldividesinto2identicaldaughtercells", "answer": "user-input", "date-added": "10/06/2021" } } };
  let json = JSON.stringify(obj);
  Logger.log(`makejson: ${json}`);
  return json;
}

function changejson() {
  let json = makejson();
  Logger.log(`changejson: ${json}`);
  let obj = JSON.parse(json);
  obj['Quizname']['1']['option2'] = "SMTP";//Changed option2 in question one to SMTP
  let json2 = JSON.stringify(obj);
  Logger.log(`json2:${json2}`);
}

Execution log
8:26:04 AM  Notice  Execution started
8:26:06 AM  Info    makejson: {"Quizname":{"1":{"question-type":"multiple-choice","question":"Findtheoddoneout?","option1":"FTP","option2":"POP","option3":"TCP","answer":"POP","date-added":"10/06/2021"},"2":{"question-type":"checkbox","question":"Whichofthefollowingarenotplanets?","option1":"Earth","option2":"Sun","option3":"Jupiter","option4":"Mars","option5":"Pluto","answer":"Sun,Pluto","date-added":"10/06/2021"},"3":{"question-type":"Input-text","question":"Inyourownwords,describeMitosis?","user-input":"Mitosisisaprocesswhereasinglecelldividesinto2identicaldaughtercells","answer":"user-input","date-added":"10/06/2021"}}}
8:26:06 AM  Info    changejson: {"Quizname":{"1":{"question-type":"multiple-choice","question":"Findtheoddoneout?","option1":"FTP","option2":"POP","option3":"TCP","answer":"POP","date-added":"10/06/2021"},"2":{"question-type":"checkbox","question":"Whichofthefollowingarenotplanets?","option1":"Earth","option2":"Sun","option3":"Jupiter","option4":"Mars","option5":"Pluto","answer":"Sun,Pluto","date-added":"10/06/2021"},"3":{"question-type":"Input-text","question":"Inyourownwords,describeMitosis?","user-input":"Mitosisisaprocesswhereasinglecelldividesinto2identicaldaughtercells","answer":"user-input","date-added":"10/06/2021"}}}
8:26:06 AM  Info    json2:{"Quizname":{"1":{"question-type":"multiple-choice","question":"Findtheoddoneout?","option1":"FTP","option2":"SMTP","option3":"TCP","answer":"POP","date-added":"10/06/2021"},"2":{"question-type":"checkbox","question":"Whichofthefollowingarenotplanets?","option1":"Earth","option2":"Sun","option3":"Jupiter","option4":"Mars","option5":"Pluto","answer":"Sun,Pluto","date-added":"10/06/2021"},"3":{"question-type":"Input-text","question":"Inyourownwords,describeMitosis?","user-input":"Mitosisisaprocesswhereasinglecelldividesinto2identicaldaughtercells","answer":"user-input","date-added":"10/06/2021"}}}
8:26:06 AM  Notice  Execution completed
  • Related