I'm using ImportJSON script that is well know to run an API and retrieve data. This works fine, I've used it many times before. However this particular API I'm running returns data that has different size rows, so I get the error:
Error
Exception: The number of columns in the data does not match the number of columns in the range. The data has 10 but the range has 17.
My code (with url hidden since it contains API credentials)
dataArray = ImportJSON(url)
shTest.getRange(1,1,dataArray.length,dataArray[0].length).setValues(dataArray);
Is there a way for me to display the results on my sheet, without looping through the array and rebuilding it so that all rows have the same amount of columns?
It's doing what it's supposed to do, and getting the correct data, just as I said correct data results in differing size rows.
Although I'm not sure about your actual values, from your error message, I guessed that all arrays in the 2-dimensional array dataArray
do not have the same length. So, as another approach, how about the following modification?
dataArray = ImportJSON(url)
shTest.getRange(1,1,dataArray.length,dataArray[0].length).setValues(dataArray);
dataArray = ImportJSON(url);
// --- I added the below script. ref: https://github.com/tanaikech/UtlApp?tab=readme-ov-file#uniform2darray
const maxLen = Math.max(...dataArray.map((r) => r.length));
dataArray = dataArray.map((r) => [...r, ...Array(maxLen - r.length).fill(null)]);
// ---
shTest.getRange(1,1,dataArray.length,dataArray[0].length).setValues(dataArray);
In this modification, all arrays in a 2-dimensional array, dataArray,
are of the same length by the inserted script.