0

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.

Yuri Khristich
  • 13,448
  • 2
  • 8
  • 23
Roberto Flores
  • 775
  • 2
  • 12
  • 46
  • I have to apologize for my poor English skill. Unfortunately, I cannot understand `I would like to format it like the following screenshot below (data there are examples):`. Your image is the output situation? If it's so, can you provide the sample input situation? And, can I ask you about the relationship between your script and your image? – Tanaike Oct 12 '21 at 01:36
  • @Tanaike: So the image that I am showing is an example that I would like to pass the values in JSON. I have added the other function where it extracts the google forms questions and answers. – Roberto Flores Oct 12 '21 at 01:50
  • Thank you for replying and updating your question. I saw your updated script. In order to test the script, can you provide the sample values of `form_title, typeofquestion, question, typeofanswers, correctanswer` of `function sendExtractedData(form_title, typeofquestion, question, typeofanswers, correctanswer) {`? I thought that those values are the input values. Is my understanding correct? – Tanaike Oct 12 '21 at 01:52
  • By the way, what is `dateAdded`? It seems that this is not used in your script. – Tanaike Oct 12 '21 at 01:53
  • @Tanaike: For the sample values, it would be like the image that I provide. The values can be multiple choice choices, checkboxes, etc. – Roberto Flores Oct 12 '21 at 01:54
  • @Tanaike: For the dateAdded, I would like to add that in the JSON. As seen in the image that I provided. – Roberto Flores Oct 12 '21 at 01:55
  • @Tanaike: The values are inputted in the google forms. I extract the google forms questions and answers – Roberto Flores Oct 12 '21 at 06:06
  • Hi, the input JSON you provided is not valid (`”` should be `'` or `"`, and some commas are missing, and `“QuizName” :` shouldn't be there). Is there a possibility of this being fixed? – Iamblichus Oct 12 '21 at 08:40

1 Answers1

0
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
Cooper
  • 59,616
  • 6
  • 23
  • 54
  • In your example, I would need to manually enter the questions, question types, etc? Also, for the "1", is there a way to have it increment based on how many questions there are in the array? – Roberto Flores Oct 12 '21 at 05:42
  • In the second function I changed the value of option1 to "white" – Cooper Oct 12 '21 at 06:33
  • Changing the keys is little is discussed [here](https://stackoverflow.com/questions/4647817/javascript-object-rename-key) – Cooper Oct 12 '21 at 06:36
  • still a little confused. My first question is: In the example that I provided, I'm guessing I would need to do a for loop to add the other questions correct? – Roberto Flores Oct 12 '21 at 06:42
  • The execution log is just showing what the Logger.log() command is displaying at different points in the code. I could have labeled each one but I didn't want to go to the trouble. Yes a loop would probably be appropriate. – Cooper Oct 12 '21 at 06:46
  • I didn't use your example because you posted it as an image and I can't copy the text from an image. I'd recommend posting it as code next time so that we can copy and paste it. We don't like to type any more than necessary. – Cooper Oct 12 '21 at 06:48
  • ok. I have uploaded the code instead of an image. – Roberto Flores Oct 12 '21 at 06:51
  • It's not valid JSON as it stands now. You can check it [here](https://jsonformatter.curiousconcept.com/) – Cooper Oct 12 '21 at 06:54
  • If you want to loop through all of the question then please provide [mcve] and more detail as to what you want to accomplish – Cooper Oct 12 '21 at 14:33
  • Thank you. Was able to figure it out using push() which simplified my code – Roberto Flores Oct 17 '21 at 08:58