I'm working on a piece of code that will convert two columns (A, B) into key/value pairs with JSON formatting. I can't figure out how to make it work. I currently have a function that will read the top row (keys) and the bottom row of the values, but I can't get it to show the rows in between. I'm not an engineer or a developer, but I do enjoy coding.
The sheet looks like this:
+-------+-------------+ | A | B | +-------+-------------+ | code | description | +-------+-------------+ | brand | microsoft | +-------+-------------+ | size | large | +-------+-------------+ | color | green | +-------+-------------+
And I'm expecting to get a JSON string like this:
[{"code":"brand","description":"microsoft"}, {"code":"color","description":"green"}, {"code":"size","description":"large"}]
So far my Google Apps Script code looks like this:
function tableJSON(arr) {
var i, j, obj = {};
for (j = 0; j < arr[0].length; j++) {
obj[arr[0][j]] = {};
}
for (i = 0; i < arr.length; i++) {
for (j = 0; j < arr[0].length; j++) {
obj[arr[0][j]] = arr[i][j];
}
}
return JSON.stringify(obj);
}
And the result when I type
="[" & tableJSON(A1:B4) & "]"is:
[{"code":"size","description":"large"}]
I'm sure the solution is simple, but I haven't been able to figure it out.
Issue:
The code only creates 1 object and rewrites the same object each time in iteration.
Solution:
Shift the 2D array to get headers
Map the array to a object