院卒新人サラリーマンのメモ代わり

備忘としてのメモを記載

gasでスプレッドシートをjsonで返す

function doGet(e){
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var json = createJSON(sheetToJsonObj(sheet))
  return json
}

// スプレッドシートからjsonObjを作る
function sheetToJsonObj(sheet) {
  var sheetVals = sheet.getDataRange().getValues();
  
  var colTitle = sheetVals.shift()
  var jsonObj = []
  sheetVals.forEach(function(row){
    var newRecord = {}
    row.forEach(function(el,idx){
      newRecord[colTitle[idx]] = el
    })
    jsonObj.push(newRecord)
  })
  return jsonObj
}

// jsonObjからjsonを作る
function createJSON(data){
  var jsonString = JSON.stringify(data)
  var mimeType = ContentService.MimeType.JSON
  var json = ContentService.createTextOutput(jsonString).setMimeType(mimeType)
  return json
}