I need to retrieve some data from a Google Spreadsheet via App Script for which I set up a DoGet function. Currently I´m retrieving an array but a I need data comes as JSON key-value pairs format.
The table on Google Sheets looks like this:
the DoGet function is set up like this:
function doGet(e) {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var returnData = sheet.getRange('A1:B2').getValues()
return ContentService.createTextOutput(JSON.stringify(returnData))
}
I´m retriving this:
[
["fruit", "vegetable"],
["ABC", "DEF"]
]
I need to retrieve JSON key:value pairs like this:
{
"fruit": "ABC",
"vegetable": "DEF"
}
2
Answers
The problem is that you are extracting a value from a Google Sheet, so this response is how your data is represented on your sheet.
You can obviously map your data in order to get the response that you want.
but this comes with a problem, what if you have more rows, how would you handle it then?
You can leverage on
Array:slice
andArray:map
functions in and accomplish your expected output.Refer the below code :