Using scripts to populate a Google Sheet with data from Postman

I'm currently working on populating a Google sheet using apps script. The task involves receiving a JSON object from Postman via POST request. The structure of the object is as follows:

{
     "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="84eee0ebe1c4e3e9e5ede8aae7ebe9">[email protected]</a>",
     "full_name": "John Doe",
     "score": 4.0,
     "max_score": 5.0
     "attempt_starttime": "2021-09-21T03:28:13+0000",
     "attempt_endtime":"2021-09-21T03:28:35+0000",
     "invited_on":"2021-09-21T03:27:50+0000",
     "percentage_score":100.0,
}

It's essential that the format and order of the data remain consistent. After modifying the data, it gets inserted into this specific Google Sheet: Google Sheet

I need assistance with initially populating the sheet with data solely from the JSON object, as I'm encountering challenges in doing so. Additionally, I'm looking to convert timestamps into days of the week and perform calculations on them. Given my limited experience with Apps Script and Postman, any guidance would be greatly appreciated.

Thank you.

This is what my current progress looks like:

function doPost(e) {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const ws = ss.getSheetByName("Sheet1"); 
  const headers = ws.getRange(1, 1, 1, ws.getLastColumn()).getValues()[0];
  const dataHeaders = headers.slice()
  const body = e.postData.contents;
  const jsonBody = JSON.parse(body);
  const data = dataHeaders.map(h => jsonBody[h]);
  ws.appendRow(data);
}

Answer №1

To maintain the current headers, ensure to insert a line before your existing headers with the precise spelling, such as: full_name, email, score, max_score, attempt_starttime, attempt_endtime, invited_on, percentage_score and rectify any comma issues in your JSON...

For example

function myFunction() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const ws = ss.getSheetByName("Sheet1"); 
  const dataHeaders = ws.getRange(1, 1, 1, ws.getLastColumn()).getValues()[0];
  const body = `{
     "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="315b555e5471565c50585d1f525e5c">[email protected]</a>",
     "full_name": "John Doe",
     "score": 4.0,
     "max_score": 5.0,
     "attempt_starttime": "2021-09-21T03:28:13+0000",
     "attempt_endtime":"2021-09-21T03:28:35+0000",
     "invited_on":"2021-09-21T03:27:50+0000",
     "percentage_score":100.0
}`
  const jsonBody = JSON.parse(body);
  const data = dataHeaders.map(h => jsonBody[h]);
  ws.appendRow(data);
}

functions correctly https://i.sstatic.net/8na1N.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Typescript: The .ts file does not recognize the definition of XMLHttpRequest

I have encountered an issue with a .ts file containing the following code: var xhttp = new XMLHttpRequest(); After running the grunt task to compile the ts files using typescript, no errors were reported. However, when I attempt to instantiate the class ...

What is the process for incorporating JavaScript files into an Angular project?

I have a template that works perfectly fine on Visual Studio. However, when I try to use it on my Angular project, I encounter an issue with the JavaScript code. I have filled the app.component.html file with the corresponding HTML code and imported the ...

What is the best way to reveal the square's id value upon hovering over it exclusively?

In this assignment, I am refraining from using HTML and focusing on JavaScript to create functionality. Here's my progress so far: document.addEventListener("DOMContentLoaded", function () { let button = document.createElement('button' ...

How can I use a Groovy Script to efficiently sort this JSON payload by a specific key?

When working with a REST API call that returns a JSON payload, I need to sort the results based on a specific key within the payload. Using Groovy for this task, I have prepared a sample of the JSON data that requires sorting: // Sample JSON body for test ...

Remove entire objects from a JSON structure if they do not contain any key-value pairs

I want to filter out objects from a JSON file that do not contain specific keys such as: "transaction_date", "asset_description", "asset_type", "type", and "amount". Here is an excerpt of the JSON file: { "first_name": { "0": "Thomas", ...

Accessing the current playback time and setting a function to trigger upon reaching the end with THREE

I have successfully implemented a method in my Three.js app for loading, playing, and analyzing audio that is compatible with both desktop and mobile devices. I must use THREE.Audio instead of HTML5 Audio Analyser, as the latter does not work on mobile dev ...

Switching between height: 0 and height:auto dynamically with the power of JavaScript and VueJS

Currently, I am changing the height of a container from 0px to auto. Since I do not know the exact final height needed for the container, using max-height could be an option but I prefer this method. The transition from 0 to auto works smoothly, however, ...

Displaying Multiple HighCharts on a single AngularJS page

As a beginner with HighCharts, I am working on adding two Highcharts to the same page that will access the same data source but display different pieces of data for each graph. For example, the categories will remain constant while the series[] will vary. ...

What is the best way to horizontally align two React components?

I'm facing an issue with aligning two React components horizontally next to each other. I've been using Material-UI's Grid for alignment, but the components InputVariables and Chart are currently stacking on top of each other in two rows ins ...

What is the best way to split a JSON array in a Hive table into batches based on a specified batch size?

Suppose we have a hive table structured as follows: id entities 1 [{"a": "a1", "b": "b1"}, {"a": "a2", "b": "b2"}, {"a": "a3", "b": "b ...

The integration of Tinymce and Vuetify dialog is causing issues where users are unable to input text in the source code editor or add code samples

Having an issue with the Vuetify dialog and TinyMCE editor. Upon opening the dialog with the editor inside, certain functionalities like Edit source code or Insert code sample are not working as intended. Specifically, when attempting to use one of these p ...

Using Three.js to extract Vertex Colors based on the z-coordinate of Vectors

Here is a sample: http://jsfiddle.net/c3shonu7/1/ The code demonstrates the creation of a BufferGeometry object by cloning an IcosahedronBufferGeometry's vertices. The goal is to apply a color gradient to the subdivided icosahedron, with lighter shad ...

Tips for converting the Instagram cURL post request to a JavaScript request

I am attempting to convert the code I received from Instagram into a token. The code provided in the Instagram DOCS uses a curl request, but I would like to implement it using JavaScript instead. Here is how the original code looks: curl -X POST &bsol ...

Find the total number of table rows that exist between two specific rows using jQuery

<table> <tr id="family_1"> <td>Family 1</td> </tr> <tr class="member"> <td>Member 1</td> </tr> <tr class="member"> <td>Member 2</td> </tr> ... <tr ...

Creating a Vue application without the use of vue-cli and instead running it on an express

Vue has an interesting feature where vue-cli is not necessary for running it without a server. Initially, I thought otherwise. The Vue installation page at https://v2.vuejs.org/v2/guide/installation.html mentions using a script under CDN. <script src=&q ...

Checking for equality between two JSON objects using Express JS

I have a question regarding my code using expressjs. I am attempting to compare two JSON objects and if they match, I want to increment a variable that was previously defined. Can you please help me identify any errors in my code? app.get('/comp&apos ...

Retrieve information from a pair of models

Hey there, I need some help. Can someone please guide me on how to obtain the 'topics' array and append it to res.view()? I've tried multiple approaches but keep getting 'undefined' in the 'topics' array. Subjects.qu ...

Extracting information from a designated website using Python, including pages with search functionality and javascript features

Visit the website where you will find a search input box in html. Input a company name into the search box, select the first suggestion from the drop-down menu (like "Anglo American plc"), navigate to the URL containing information about that specific com ...

When attempting to open a link in a new tab, the ng-click function fails to execute

In Angular, utilizing both the <code>ng-click and ng-href directives at the same time will result in the click function being executed first. In this scenario, clicking on a link that navigates to Google will be prevented and instead an alert will be ...

Issue: Angular JS radio input not functioning as expected

Below is the code snippet in question: <div ng-controller="TestController"> <input ng-repeat="item in array" ng-model="selected.name" value="{{item.name}}" type="radio"></input> </div> <script type="text/javascript"> ...