How to export JSON-like data in spreadsheet column to json file?

683 Views Asked by At

I have a Google sheet with JSON-like data in a column and would like to export this column as a JSON file. I have tried using javascript along with xlsx package to convert the sheet to json file but it adds backslashes to the column and cannot be parsed (throws syntax error) using JSON.parse() as it does not recognise it as valid json. Any help is appreciated! enter image description here

let xlsx = require("xlsx")
let path = require("path")
let fs = require("fs");
const inputFilePath = path.join(__dirname, './Sample.xlsx');
let File = xlsx.readFile(inputFilePath);
let content = xlsx.utils.sheet_to_json(File.Sheets['Sheet1']);
console.log(JSON.parse(content[0]["content"])); //throws error
1

There are 1 best solutions below

2
On BEST ANSWER

Here is an example that will write the data without backslash (do not use JSON.stringify in this case). The file will be in 'test' folder here, that you have to create or change in the script.

// you need to activate the Advanced Drive Service (Drive Activity API).
function test() {
  var content = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange('A1').getValue();
  var folders = DriveApp.getFoldersByName("test");
  if (folders.hasNext()) {
    var folder = folders.next();
    saveData(folder, 'myJSON.json',content);
  }
}
function saveData(folder, fileName, content) {
  var children = folder.getFilesByName(fileName);
  var file = null;
  if (children.hasNext()) {
    file = children.next();
    file.setContent(content);
  } else {
    file = folder.createFile(fileName, content);
  }
}

https://docs.google.com/spreadsheets/d/1PWzdlaZi2m0a1xDiqLp2eJXIvx-AyvZ16CQW362q-Nw/edit?usp=sharing Of course, replace A1 by B2 for your file. enter image description here