I have some data in a Google sheet that I want to convert to a .json file using Google Apps Script, however I am struggling to figure out the best way to approach it. I have an implementation already that successfully converts data from sheets into a .json but doesn’t achieve the structure that I want.
The structure I want in my .json is as follows:
{ "name": "Adam", "options": { "option1": True, "option2": True, "option3": False }, "data": [ "data1", "data2", "data3" ] }
When I read the raw data from Google sheets using:
var data = sheet.getDataRange().getValues()
I get this stored in data:
[[name, Adam, ], [options, option1, true], [, option2, true], [, option3, false], [data, data1, ], [, data2, ], [, data3, ]]
The empty items in the lists are there as some rows don’t extend to the full range of the data, this is intentional as the number of columns on each row indicate the ‘level’ or ‘nest’ of the .json structure.
I cannot figure out a way to convert this list of lists to the desired .json format, I figured a recursive function could be sufficient but for the life of me cannot figure it out.
I’ve tried various ways to looping through the loop and checking for conditions, where it’ll create a dictionary or list depending on the surrounding data but can’t figure out an algorithm that can scale to bigger ranges of data.
2
Answers
From your showing sample value and question, I guessed that your Spreadsheet might be in the following situation.
And, you want to retrieve the object
{"name":"Adam","options":{"option1":true,"option2":true,"option3":false},"data":["data1","data2","data3"]}
from the above Spreadsheet.If my understanding is correct, how about the following sample script?
Sample script:
When this script is run, when the value of
data
is[["name","Adam",""],["options","option1",true],["","option2",true],["","option3",false],["data","data1",""],["","data2",""],["","data3",""]]
,{"name":"Adam","options":{"option1":true,"option2":true,"option3":false},"data":["data1","data2","data3"]}
is returned.Testing:
When this script is tested, the following result is obtained.
Reference:
I assumed data as follows:
GS:
JSON: