Last active
August 2, 2026 15:25
-
-
Save YogaSakti/9f1f42c075cefe4043aac67298b07e08 to your computer and use it in GitHub Desktop.
ImportJSON by Yoga Sakti, Brad Jasper and Trevor Lohrbeer - Enhanced Version
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /*====================================================================================================================================* | |
| ImportJSON by Yoga Sakti, Brad Jasper and Trevor Lohrbeer - Optimized Version | |
| ==================================================================================================================================== | |
| Version: 2.1.0 | |
| Project Page: https://github.com/bradjasper/ImportJSON | |
| Copyright: (c) 2025-2026 by Yoga Sakti | |
| (c) 2017-2019 by Brad Jasper | |
| (c) 2012-2017 by Trevor Lohrbeer | |
| License: GNU General Public License, version 3 (GPL-3.0) | |
| http://www.opensource.org/licenses/gpl-3.0.html | |
| ------------------------------------------------------------------------------------------------------------------------------------ | |
| Changelog: | |
| 2.1.0 (August 2026) - Correctness, security and performance pass over 2.0.0 | |
| FIXED (bugs that silently broke documented features) | |
| - hasOption_() now recognizes "key=value" options. In 2.0.0 it compared for exact | |
| equality, so `customSeparator=|` and every other valued option never matched and | |
| the feature was dead code. | |
| - getOptionValue_() now accepts a string OR an array of options, and no longer | |
| truncates values containing "=" (was `split('=')[1]`). | |
| - toTitleCase_() no longer uses the deprecated substr() (2.0.0 claimed this was | |
| already done; it was not). | |
| - defaultTransform_() no longer stringifies every cell. Numbers, booleans and dates | |
| keep their type so the sheet can compute on them. Truncation applies to strings only. | |
| - getDataFromNamedSheet_() reads display values, so numbers/dates inside the JSON text | |
| are no longer coerced by the sheet locale (1000000 -> "1E+06") and JSON.parse survives. | |
| - Removed the console.log() that dumped full sheet JSON (including any tokens) to logs. | |
| - "noHeaders" on an empty result returns [[""]] instead of [], which rendered as a | |
| cell error. | |
| - Removed `timeout: 30000` from fetch options — UrlFetchApp has no such option. | |
| - Removed the suspiciousPatterns block: it was unreachable for its stated purpose | |
| (the http(s) prefix test already runs first) and rejected legitimate URLs such as | |
| https://api.example.com/data:2026 because /data:/ was not anchored to the scheme. | |
| ADDED | |
| - Response caching via CacheService (default 1 hour). Custom functions re-run on every | |
| recalculation; without a cache a sheet with N ImportJSON cells burns N UrlFetchApp | |
| quota units per open. Options: `noCache`, `cacheSeconds=N`. | |
| - SSRF guard: blocks localhost, link-local, cloud metadata and RFC1918 hosts. | |
| - Recursion depth guard (`maxDepth=N`, default 64) against pathological JSON. | |
| - ImportJSONWithStoredAuth() reads credentials from Script Properties instead of | |
| embedding them in a sheet formula where every viewer can read them. | |
| - Error cells are sanitized and truncated so an upstream error body cannot dump | |
| internal detail into the spreadsheet. | |
| - removeCommonPrefixes_() trims the shared prefix back to a path boundary, so | |
| "/name" + "/nation" yield "Name"/"Nation" instead of "Me"/"Tion". | |
| ------------------------------------------------------------------------------------------------------------------------------------ | |
| Original Changelog (from bradjasper/ImportJSON): | |
| 1.6.0 (June 2, 2019) Fixed null values (thanks @gdesmedt1) | |
| 1.5.0 (January 11, 2019) Adds ability to include all headers in a fixed order | |
| 1.4.0 (July 23, 2017) Transfer project to Brad Jasper. Fixed bugs. Added ImportJSONFromSheet and ImportJSONBasicAuth. | |
| 1.3.0 Adds ability to import the text from a set of rows containing the text to parse | |
| 1.2.1 Fixed a bug with how nested arrays are handled | |
| 1.2.0 Added ImportJSONViaPost and support for fetchOptions | |
| 1.1.1 Added version number using Google Scripts Versioning | |
| 1.1.0 Added support for the noHeaders option | |
| 1.0.0 Initial release | |
| *====================================================================================================================================*/ | |
| /** Default cache lifetime, in seconds, for fetched responses. */ | |
| const IMPORTJSON_DEFAULT_CACHE_SECONDS = 3600; | |
| /** Hard ceiling CacheService allows for a single value, in bytes. */ | |
| const IMPORTJSON_MAX_CACHE_BYTES = 100000; | |
| /** Default truncation length applied to string cells. */ | |
| const IMPORTJSON_DEFAULT_MAX_LENGTH = 256; | |
| /** Default recursion depth limit while walking the JSON tree. */ | |
| const IMPORTJSON_DEFAULT_MAX_DEPTH = 64; | |
| /** Longest error message written into a cell. */ | |
| const IMPORTJSON_MAX_ERROR_LENGTH = 300; | |
| /** | |
| * Imports a JSON feed and returns the results to be inserted into a Google Spreadsheet. The JSON feed is flattened to | |
| * create a two-dimensional array. The first row contains the headers, with each column header indicating the path to | |
| * that data in the JSON feed. The remaining rows contain the data. | |
| * | |
| * @param {string} url the URL to a public JSON feed | |
| * @param {string} query a comma-separated list of paths to import | |
| * @param {string} parseOptions a comma-separated list of options that alter processing of the data | |
| * @customfunction | |
| * @return {Array<Array>} a two-dimensional array containing the data, with the first row containing headers | |
| */ | |
| function ImportJSON(url, query, parseOptions) { | |
| return ImportJSONAdvanced(url, null, query, parseOptions, includeXPath_, defaultTransform_); | |
| } | |
| /** | |
| * Imports a JSON feed with full control over the fetch, the path filter and the cell transform. | |
| * | |
| * @param {string} url the URL to a JSON feed | |
| * @param {Object} fetchOptions options passed to UrlFetchApp.fetch() | |
| * @param {string} query a comma-separated list of paths to import | |
| * @param {string} parseOptions a comma-separated list of options that alter processing of the data | |
| * @param {Function} includeFunc receives (query, path, options) and returns whether to include the path | |
| * @param {Function} transformFunc receives (data, row, column, options) and rewrites the cell in place | |
| * @return {Array<Array>} a two-dimensional array containing the data | |
| */ | |
| function ImportJSONAdvanced(url, fetchOptions, query, parseOptions, includeFunc, transformFunc) { | |
| try { | |
| validateUrl_(url); | |
| const optionsArray = toOptionsArray_(parseOptions); | |
| const jsonText = fetchJSONText_(url, fetchOptions, optionsArray); | |
| let object; | |
| try { | |
| object = JSON.parse(jsonText); | |
| } catch (parseError) { | |
| throw new Error(`Invalid JSON format: ${parseError.message}`); | |
| } | |
| return parseJSONObject_(object, query, optionsArray, includeFunc, transformFunc); | |
| } catch (error) { | |
| return errorResult_('ImportJSON', error); | |
| } | |
| } | |
| /** | |
| * Imports a JSON feed retrieved with a POST request. | |
| * | |
| * @param {string} url the URL to a JSON feed | |
| * @param {string} payload the POST body | |
| * @param {string} fetchOptions a comma-separated list of key=value options passed to UrlFetchApp.fetch() | |
| * @param {string} query a comma-separated list of paths to import | |
| * @param {string} parseOptions a comma-separated list of options that alter processing of the data | |
| * @customfunction | |
| * @return {Array<Array>} a two-dimensional array containing the data | |
| */ | |
| function ImportJSONViaPost(url, payload, fetchOptions, query, parseOptions) { | |
| try { | |
| validateUrl_(url); | |
| const postOptions = parseToObject_(fetchOptions); | |
| if (isBlank_(postOptions.method)) postOptions.method = 'POST'; | |
| if (isBlank_(postOptions.payload)) postOptions.payload = payload; | |
| if (isBlank_(postOptions.contentType)) postOptions.contentType = 'application/x-www-form-urlencoded'; | |
| ['validateHttpsCertificates', 'followRedirects', 'muteHttpExceptions', 'escaping'] | |
| .forEach(key => convertToBool_(postOptions, key)); | |
| return ImportJSONAdvanced(url, postOptions, query, parseOptions, includeXPath_, defaultTransform_); | |
| } catch (error) { | |
| return errorResult_('ImportJSONViaPost', error); | |
| } | |
| } | |
| /** | |
| * Imports JSON that is stored as text inside a sheet, rather than fetched over HTTP. | |
| * | |
| * @param {string} sheetName name of the sheet holding the JSON text in column A | |
| * @param {string} query a comma-separated list of paths to import | |
| * @param {string} parseOptions a comma-separated list of options that alter processing of the data | |
| * @customfunction | |
| * @return {Array<Array>} a two-dimensional array containing the data | |
| */ | |
| function ImportJSONFromSheet(sheetName, query, parseOptions) { | |
| try { | |
| if (!sheetName || typeof sheetName !== 'string') { | |
| throw new Error('Invalid sheet name provided'); | |
| } | |
| const object = getDataFromNamedSheet_(sheetName); | |
| return parseJSONObject_(object, query, toOptionsArray_(parseOptions), includeXPath_, defaultTransform_); | |
| } catch (error) { | |
| return errorResult_('ImportJSONFromSheet', error); | |
| } | |
| } | |
| /** | |
| * Imports a JSON feed protected by HTTP basic auth. | |
| * | |
| * SECURITY: credentials passed here are stored in the cell formula and are visible to anyone who can | |
| * read the spreadsheet, and travel with any copy of it. Prefer ImportJSONWithStoredAuth(). | |
| * | |
| * @param {string} url the URL to a JSON feed | |
| * @param {string} username the basic auth username | |
| * @param {string} password the basic auth password | |
| * @param {string} query a comma-separated list of paths to import | |
| * @param {string} parseOptions a comma-separated list of options that alter processing of the data | |
| * @customfunction | |
| * @return {Array<Array>} a two-dimensional array containing the data | |
| */ | |
| function ImportJSONBasicAuth(url, username, password, query, parseOptions) { | |
| try { | |
| validateUrl_(url); | |
| if (!username || !password) { | |
| throw new Error('Username and password are required for basic auth'); | |
| } | |
| return ImportJSONAdvanced(url, basicAuthOptions_(username, password), query, parseOptions, | |
| includeXPath_, defaultTransform_); | |
| } catch (error) { | |
| return errorResult_('ImportJSONBasicAuth', error); | |
| } | |
| } | |
| /** | |
| * Imports a JSON feed protected by HTTP basic auth, reading the credentials from Script Properties | |
| * so they never appear in a cell formula. | |
| * | |
| * Store them once from the script editor: | |
| * PropertiesService.getScriptProperties().setProperties({ | |
| * 'myapi.user': 'alice', | |
| * 'myapi.pass': 's3cret' | |
| * }); | |
| * | |
| * Then call: =ImportJSONWithStoredAuth("https://api.example.com/x", "myapi.user", "myapi.pass") | |
| * | |
| * @param {string} url the URL to a JSON feed | |
| * @param {string} usernameKey Script Property key holding the username | |
| * @param {string} passwordKey Script Property key holding the password | |
| * @param {string} query a comma-separated list of paths to import | |
| * @param {string} parseOptions a comma-separated list of options that alter processing of the data | |
| * @customfunction | |
| * @return {Array<Array>} a two-dimensional array containing the data | |
| */ | |
| function ImportJSONWithStoredAuth(url, usernameKey, passwordKey, query, parseOptions) { | |
| try { | |
| validateUrl_(url); | |
| if (!usernameKey || !passwordKey) { | |
| throw new Error('Both usernameKey and passwordKey are required'); | |
| } | |
| const props = PropertiesService.getScriptProperties(); | |
| const username = props.getProperty(usernameKey); | |
| const password = props.getProperty(passwordKey); | |
| if (!username || !password) { | |
| throw new Error('Credentials not found in Script Properties'); | |
| } | |
| return ImportJSONAdvanced(url, basicAuthOptions_(username, password), query, parseOptions, | |
| includeXPath_, defaultTransform_); | |
| } catch (error) { | |
| return errorResult_('ImportJSONWithStoredAuth', error); | |
| } | |
| } | |
| /** | |
| * Imports a JSON feed using custom request headers. Useful for APIs requiring a specific | |
| * content type, an API key header or CSRF protection. | |
| * | |
| * @param {string} url the URL to a JSON feed | |
| * @param {string} headersJson JSON string of headers, e.g. '{"content-type":"application/json"}' | |
| * @param {string} query a comma-separated list of paths to import | |
| * @param {string} parseOptions a comma-separated list of options that alter processing of the data | |
| * @customfunction | |
| * @return {Array<Array>} a two-dimensional array containing the data | |
| */ | |
| function ImportJSONWithHeaders(url, headersJson, query, parseOptions) { | |
| try { | |
| validateUrl_(url); | |
| let customHeaders = {}; | |
| if (headersJson && String(headersJson).trim() !== '') { | |
| try { | |
| customHeaders = JSON.parse(headersJson); | |
| } catch (e) { | |
| throw new Error('Invalid headers JSON format'); | |
| } | |
| } | |
| if (!isObject_(customHeaders)) { | |
| throw new Error('Headers JSON must describe an object'); | |
| } | |
| return ImportJSONAdvanced(url, { headers: customHeaders }, query, parseOptions, | |
| includeXPath_, defaultTransform_); | |
| } catch (error) { | |
| return errorResult_('ImportJSONWithHeaders', error); | |
| } | |
| } | |
| /** | |
| * Encodes a value for safe inclusion in a URL. | |
| * | |
| * @param {string} value the value to encode | |
| * @customfunction | |
| * @return {string} the percent-encoded value | |
| */ | |
| function URLEncode(value) { | |
| return encodeURIComponent(String(value)); | |
| } | |
| /*====================================================================================================================================* | |
| Fetching | |
| *====================================================================================================================================*/ | |
| /** | |
| * Fetches the raw response body, serving it from the script cache when possible. | |
| * Caching matters here because custom functions re-run on every recalculation; without it, | |
| * a sheet with many ImportJSON cells exhausts the daily UrlFetchApp quota. | |
| */ | |
| function fetchJSONText_(url, fetchOptions, optionsArray) { | |
| const cacheSeconds = resolveCacheSeconds_(optionsArray); | |
| const cache = cacheSeconds > 0 ? tryGetCache_() : null; | |
| const cacheKey = cache ? buildCacheKey_(url, fetchOptions) : null; | |
| if (cache) { | |
| const cached = cache.get(cacheKey); | |
| if (cached !== null) { | |
| return cached; | |
| } | |
| } | |
| const finalFetchOptions = Object.assign({ | |
| muteHttpExceptions: true, | |
| validateHttpsCertificates: true, | |
| followRedirects: true | |
| }, fetchOptions || {}); | |
| const response = UrlFetchApp.fetch(url, finalFetchOptions); | |
| const responseCode = response.getResponseCode(); | |
| if (responseCode < 200 || responseCode >= 300) { | |
| // The body is deliberately not included: it can carry upstream internal detail | |
| // that would then be written into a visible spreadsheet cell. | |
| throw new Error(`HTTP Error ${responseCode} from ${safeHost_(url)}`); | |
| } | |
| const jsonText = response.getContentText(); | |
| if (!jsonText || jsonText.trim() === '') { | |
| throw new Error('Empty response received from URL'); | |
| } | |
| if (cache && jsonText.length < IMPORTJSON_MAX_CACHE_BYTES) { | |
| try { | |
| cache.put(cacheKey, jsonText, cacheSeconds); | |
| } catch (e) { | |
| // A cache write failure must never fail the import. | |
| } | |
| } | |
| return jsonText; | |
| } | |
| function resolveCacheSeconds_(optionsArray) { | |
| if (hasOption_(optionsArray, 'noCache')) { | |
| return 0; | |
| } | |
| const raw = getOptionValue_(optionsArray, 'cacheSeconds'); | |
| if (raw === null) { | |
| return IMPORTJSON_DEFAULT_CACHE_SECONDS; | |
| } | |
| const parsed = parseInt(raw, 10); | |
| if (isNaN(parsed) || parsed <= 0) { | |
| return 0; | |
| } | |
| // CacheService caps a single entry at 6 hours. | |
| return Math.min(parsed, 21600); | |
| } | |
| function tryGetCache_() { | |
| try { | |
| return CacheService.getScriptCache(); | |
| } catch (e) { | |
| return null; | |
| } | |
| } | |
| function buildCacheKey_(url, fetchOptions) { | |
| const material = url + '|' + (fetchOptions ? JSON.stringify(fetchOptions) : ''); | |
| const digest = Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, material, Utilities.Charset.UTF_8); | |
| let key = 'ijson_'; | |
| for (const byte of digest) { | |
| key += ((byte & 0xFF) + 0x100).toString(16).substring(1); | |
| } | |
| return key; | |
| } | |
| function basicAuthOptions_(username, password) { | |
| const encoded = Utilities.base64Encode(`${username}:${password}`); | |
| return { | |
| headers: { | |
| Authorization: `Basic ${encoded}`, | |
| 'User-Agent': 'Google Apps Script ImportJSON' | |
| } | |
| }; | |
| } | |
| /*====================================================================================================================================* | |
| URL validation | |
| *====================================================================================================================================*/ | |
| /** | |
| * Validates that the URL is a well-formed http(s) URL that does not point at a private | |
| * or metadata address. Blocking those matters because Apps Script runs the fetch, so an | |
| * attacker-controlled URL in a shared sheet would otherwise reach internal endpoints. | |
| */ | |
| function validateUrl_(url) { | |
| if (!url || typeof url !== 'string') { | |
| throw new Error('URL must be a non-empty string'); | |
| } | |
| const match = /^(https?):\/\/([^\/?#]+)/i.exec(url.trim()); | |
| if (!match) { | |
| throw new Error('URL must start with http:// or https://'); | |
| } | |
| const host = stripCredentials_(match[2]).toLowerCase(); | |
| if (isPrivateHost_(host)) { | |
| throw new Error('URL points to a private or internal address'); | |
| } | |
| } | |
| function stripCredentials_(authority) { | |
| const at = authority.lastIndexOf('@'); | |
| const hostPort = at === -1 ? authority : authority.substring(at + 1); | |
| const colon = hostPort.lastIndexOf(':'); | |
| // Leave IPv6 literals ("[::1]") intact. | |
| if (colon === -1 || hostPort.indexOf(']') > colon) { | |
| return hostPort; | |
| } | |
| return hostPort.substring(0, colon); | |
| } | |
| function isPrivateHost_(host) { | |
| const bare = host.replace(/^\[|\]$/g, ''); | |
| if (bare === 'localhost' || bare === '::1' || bare === '0.0.0.0') return true; | |
| if (/\.(local|internal|localdomain)$/.test(bare)) return true; | |
| if (/^(10|127)\./.test(bare)) return true; | |
| if (/^192\.168\./.test(bare)) return true; | |
| if (/^169\.254\./.test(bare)) return true; // link-local, incl. 169.254.169.254 metadata | |
| if (/^172\.(1[6-9]|2\d|3[01])\./.test(bare)) return true; // 172.16.0.0/12 | |
| if (/^(fc|fd|fe80)/i.test(bare) && bare.indexOf(':') !== -1) return true; | |
| return false; | |
| } | |
| function safeHost_(url) { | |
| const match = /^https?:\/\/([^\/?#]+)/i.exec(String(url).trim()); | |
| return match ? stripCredentials_(match[1]) : 'the URL'; | |
| } | |
| /*====================================================================================================================================* | |
| Parsing | |
| *====================================================================================================================================*/ | |
| /** | |
| * Flattens a parsed JSON object into a two-dimensional array. | |
| */ | |
| function parseJSONObject_(object, query, options, includeFunc, transformFunc) { | |
| try { | |
| const headers = {}; | |
| const data = []; | |
| const optionsArray = toOptionsArray_(options); | |
| if (query && !Array.isArray(query)) { | |
| const queryText = query.toString(); | |
| query = queryText.indexOf(',') !== -1 | |
| ? queryText.split(',').map(q => q.trim()).filter(q => q.length > 0) | |
| : queryText.trim(); | |
| } | |
| // Prepopulating headers from the query fixes column order across sparse rows. | |
| if (hasOption_(optionsArray, 'allHeaders') && Array.isArray(query)) { | |
| query.forEach((q, i) => { | |
| headers[q] = i; | |
| }); | |
| } | |
| const maxDepth = parseIntOption_(optionsArray, 'maxDepth', IMPORTJSON_DEFAULT_MAX_DEPTH); | |
| parseData_(headers, data, '', { rowIndex: 1, depth: 0, maxDepth: maxDepth }, | |
| object, query, optionsArray, includeFunc); | |
| parseHeaders_(headers, data); | |
| transformData_(data, optionsArray, transformFunc); | |
| if (hasOption_(optionsArray, 'noHeaders')) { | |
| // Returning [] renders as a cell error, so fall back to a single blank cell. | |
| return data.length > 1 ? data.slice(1) : [['']]; | |
| } | |
| return data.length > 0 ? data : [['']]; | |
| } catch (error) { | |
| return errorResult_('parseJSONObject_', error); | |
| } | |
| } | |
| /** | |
| * Recursively walks the JSON tree, writing scalars into the data grid. | |
| * | |
| * @return {boolean} whether any data was written for this branch | |
| */ | |
| function parseData_(headers, data, path, state, value, query, options, includeFunc) { | |
| if (state.depth > state.maxDepth) { | |
| throw new Error(`JSON nesting exceeds maxDepth (${state.maxDepth})`); | |
| } | |
| let dataInserted = false; | |
| if (value === null || value === undefined) { | |
| if (!includeFunc || includeFunc(query, path, options)) { | |
| writeCell_(headers, data, path, state, hasOption_(options, 'keepNull') ? null : ''); | |
| dataInserted = true; | |
| } | |
| } else if (Array.isArray(value) && isObjectArray_(value)) { | |
| state.depth++; | |
| for (let i = 0; i < value.length; i++) { | |
| if (parseData_(headers, data, path, state, value[i], query, options, includeFunc)) { | |
| dataInserted = true; | |
| if (data[state.rowIndex]) { | |
| state.rowIndex++; | |
| } | |
| } | |
| } | |
| state.depth--; | |
| } else if (isObject_(value)) { | |
| state.depth++; | |
| for (const key in value) { | |
| if (Object.prototype.hasOwnProperty.call(value, key)) { | |
| if (parseData_(headers, data, `${path}/${key}`, state, value[key], query, options, includeFunc)) { | |
| dataInserted = true; | |
| } | |
| } | |
| } | |
| state.depth--; | |
| } else if (!includeFunc || includeFunc(query, path, options)) { | |
| let cell = value; | |
| if (Array.isArray(cell)) { | |
| const separator = getOptionValue_(options, 'customSeparator'); | |
| cell = cell.join(separator === null ? ',' : separator); | |
| } | |
| writeCell_(headers, data, path, state, cell); | |
| dataInserted = true; | |
| } | |
| return dataInserted; | |
| } | |
| function writeCell_(headers, data, path, state, value) { | |
| if (!data[state.rowIndex]) { | |
| data[state.rowIndex] = []; | |
| } | |
| if (!(path in headers)) { | |
| headers[path] = Object.keys(headers).length; | |
| } | |
| data[state.rowIndex][headers[path]] = value; | |
| } | |
| function parseHeaders_(headers, data) { | |
| data[0] = []; | |
| Object.keys(headers).forEach(key => { | |
| data[0][headers[key]] = key; | |
| }); | |
| } | |
| function transformData_(data, options, transformFunc) { | |
| if (!transformFunc) return; | |
| const columnCount = (data[0] && data[0].length) ? data[0].length : 0; | |
| let failures = 0; | |
| let firstFailure = null; | |
| for (let i = 0; i < data.length; i++) { | |
| if (!data[i]) continue; | |
| for (let j = 0; j < columnCount; j++) { | |
| try { | |
| transformFunc(data, i, j, options); | |
| } catch (error) { | |
| failures++; | |
| if (!firstFailure) firstFailure = `[${i},${j}] ${error.toString()}`; | |
| } | |
| } | |
| } | |
| // One aggregated warning, so a systematic transform failure is visible instead of | |
| // drowning in per-cell noise. | |
| if (failures > 0) { | |
| console.warn(`ImportJSON: ${failures} cell transform(s) failed. First: ${firstFailure}`); | |
| } | |
| } | |
| /*====================================================================================================================================* | |
| Cell transform | |
| *====================================================================================================================================*/ | |
| /** | |
| * Default cell transform: inherits blanks down, prettifies headers and truncates long strings. | |
| * Non-string values keep their type so the sheet can still compute on them. | |
| */ | |
| function defaultTransform_(data, row, column, options) { | |
| if (data[row][column] === null || data[row][column] === undefined) { | |
| if (row < 2 || hasOption_(options, 'noInherit')) { | |
| data[row][column] = hasOption_(options, 'keepNull') ? null : ''; | |
| } else { | |
| const inherited = data[row - 1] ? data[row - 1][column] : undefined; | |
| data[row][column] = (inherited === null || inherited === undefined) ? '' : inherited; | |
| } | |
| } | |
| if (!hasOption_(options, 'rawHeaders') && row === 0) { | |
| if (column === 0 && data[row].length > 1) { | |
| removeCommonPrefixes_(data, row); | |
| } | |
| data[row][column] = toTitleCase_(String(data[row][column]).replace(/[\/\_]/g, ' ')); | |
| } | |
| // Truncating only strings preserves numbers, booleans and dates as usable values. | |
| if (!hasOption_(options, 'noTruncate') && typeof data[row][column] === 'string' && data[row][column]) { | |
| const maxLength = parseIntOption_(options, 'maxLength', IMPORTJSON_DEFAULT_MAX_LENGTH); | |
| if (data[row][column].length > maxLength) { | |
| data[row][column] = data[row][column].substring(0, maxLength); | |
| } | |
| } | |
| if (hasOption_(options, 'debugLocation')) { | |
| data[row][column] = `[${row},${column}]${data[row][column]}`; | |
| } | |
| } | |
| /** | |
| * Identity transform: leaves every cell exactly as parsed. | |
| */ | |
| function noTransform_(data, row, column, options) { | |
| // Intentionally empty. | |
| } | |
| function removeCommonPrefixes_(data, row) { | |
| if (!data[row] || data[row].length < 2) return; | |
| let matchIndex = (data[row][0] && data[row][0].length) ? data[row][0].length : 0; | |
| for (let i = 1; i < data[row].length; i++) { | |
| matchIndex = findEqualityEndpoint_(data[row][i - 1], data[row][i], matchIndex); | |
| if (matchIndex === 0) return; | |
| } | |
| // Cut back to a path boundary so "/name" and "/nation" do not become "me" and "tion". | |
| const prefix = String(data[row][0]).substring(0, matchIndex); | |
| matchIndex = prefix.lastIndexOf('/') + 1; | |
| if (matchIndex === 0) return; | |
| for (let i = 0; i < data[row].length; i++) { | |
| if (typeof data[row][i] === 'string') { | |
| data[row][i] = data[row][i].substring(matchIndex); | |
| } | |
| } | |
| } | |
| function findEqualityEndpoint_(string1, string2, stopAt) { | |
| if (!string1 || !string2) { | |
| return 0; | |
| } | |
| const maxEndpoint = Math.min(stopAt, string1.length, string2.length); | |
| for (let i = 0; i < maxEndpoint; i++) { | |
| if (string1.charAt(i) !== string2.charAt(i)) { | |
| return i; | |
| } | |
| } | |
| return maxEndpoint; | |
| } | |
| /*====================================================================================================================================* | |
| Path filtering | |
| *====================================================================================================================================*/ | |
| function includeXPath_(query, path, options) { | |
| if (!query) { | |
| return true; | |
| } else if (Array.isArray(query)) { | |
| return query.some(q => applyXPathRule_(q, path, options)); | |
| } | |
| return applyXPathRule_(query, path, options); | |
| } | |
| function applyXPathRule_(rule, path, options) { | |
| if (path.indexOf(rule) === 0) { | |
| return true; | |
| } | |
| if (rule.indexOf('/*') === -1) { | |
| return false; | |
| } | |
| const rulePieces = rule.split('/'); | |
| const pathPieces = path.split('/'); | |
| if (rulePieces.length !== pathPieces.length) { | |
| return false; | |
| } | |
| return rulePieces.every((piece, i) => piece === '*' || piece === pathPieces[i]); | |
| } | |
| /*====================================================================================================================================* | |
| Options | |
| *====================================================================================================================================*/ | |
| /** | |
| * Normalizes options into a trimmed array. Accepts a comma-separated string, an array, or nothing. | |
| */ | |
| function toOptionsArray_(options) { | |
| if (!options) return []; | |
| if (Array.isArray(options)) return options.map(o => String(o).trim()); | |
| return String(options).split(',').map(o => o.trim()).filter(o => o.length > 0); | |
| } | |
| /** | |
| * Reports whether an option is present, as a bare flag ("noHeaders") or a valued | |
| * option ("maxLength=500"). | |
| */ | |
| function hasOption_(options, option) { | |
| if (!options) return false; | |
| const arr = toOptionsArray_(options); | |
| const prefix = option + '='; | |
| return arr.some(o => o === option || o.indexOf(prefix) === 0); | |
| } | |
| /** | |
| * Returns the value of a "key=value" option, or null. The value may itself contain "=". | |
| */ | |
| function getOptionValue_(options, optionName) { | |
| if (!options) return null; | |
| const arr = toOptionsArray_(options); | |
| const prefix = optionName + '='; | |
| for (const option of arr) { | |
| if (option.indexOf(prefix) === 0) { | |
| return option.substring(prefix.length); | |
| } | |
| } | |
| return null; | |
| } | |
| function parseIntOption_(options, optionName, fallback) { | |
| const raw = getOptionValue_(options, optionName); | |
| if (raw === null) return fallback; | |
| const parsed = parseInt(raw, 10); | |
| return (isNaN(parsed) || parsed <= 0) ? fallback : parsed; | |
| } | |
| /** | |
| * Parses a comma-separated "key=value" string into an object. | |
| * Note: values cannot contain a comma; use ImportJSONAdvanced() from a script if they must. | |
| */ | |
| function parseToObject_(text) { | |
| const map = {}; | |
| const entries = (text && String(text).trim().length > 0) ? String(text).split(',') : []; | |
| entries.forEach(entry => addToMap_(map, entry)); | |
| return map; | |
| } | |
| function addToMap_(map, entry) { | |
| const equalsIndex = entry.indexOf('='); | |
| const key = (equalsIndex !== -1) ? entry.substring(0, equalsIndex) : entry; | |
| const value = (equalsIndex !== -1) ? entry.substring(equalsIndex + 1) : ''; | |
| map[key.trim()] = value; | |
| } | |
| function toBool_(value) { | |
| return value !== null && value !== undefined && String(value).toLowerCase() === 'true'; | |
| } | |
| function convertToBool_(map, key) { | |
| if (map[key] !== null && map[key] !== undefined) { | |
| map[key] = toBool_(map[key]); | |
| } | |
| } | |
| /*====================================================================================================================================* | |
| Sheet input | |
| *====================================================================================================================================*/ | |
| /** | |
| * Reads JSON text stored across the rows of column A in a named sheet. | |
| * Display values are used so the sheet's number and date formatting cannot corrupt the JSON. | |
| */ | |
| function getDataFromNamedSheet_(sheetName) { | |
| const ss = SpreadsheetApp.getActiveSpreadsheet(); | |
| const source = ss.getSheetByName(sheetName); | |
| if (!source) { | |
| throw new Error(`Sheet '${sheetName}' not found`); | |
| } | |
| const lastRow = source.getLastRow(); | |
| if (lastRow === 0) { | |
| throw new Error(`Sheet '${sheetName}' is empty`); | |
| } | |
| const jsonValues = source.getRange(1, 1, lastRow).getDisplayValues(); | |
| let jsonText = ''; | |
| for (const row of jsonValues) { | |
| for (const cellValue of row) { | |
| if (cellValue) { | |
| jsonText += cellValue; | |
| } | |
| } | |
| } | |
| if (!jsonText.trim()) { | |
| throw new Error(`No JSON data found in sheet '${sheetName}'`); | |
| } | |
| try { | |
| return JSON.parse(jsonText); | |
| } catch (error) { | |
| throw new Error(`Sheet '${sheetName}' does not contain valid JSON: ${error.message}`); | |
| } | |
| } | |
| /*====================================================================================================================================* | |
| Small helpers | |
| *====================================================================================================================================*/ | |
| function isObject_(test) { | |
| return test !== null && typeof test === 'object' && !Array.isArray(test); | |
| } | |
| function isObjectArray_(test) { | |
| if (!test || test.length === 0) return false; | |
| return test.some(item => isObject_(item)); | |
| } | |
| function isBlank_(value) { | |
| return value === null || value === undefined || String(value).trim() === ''; | |
| } | |
| function toTitleCase_(text) { | |
| if (text === null || text === undefined) { | |
| return ''; | |
| } | |
| return String(text).replace(/\w\S*/g, (word) => | |
| word.charAt(0).toUpperCase() + word.substring(1).toLowerCase() | |
| ); | |
| } | |
| /** | |
| * Builds the two-cell error grid written into the sheet, keeping the message short and | |
| * free of upstream response bodies. | |
| */ | |
| function errorResult_(context, error) { | |
| const message = (error && error.message) ? error.message : String(error); | |
| const trimmed = message.length > IMPORTJSON_MAX_ERROR_LENGTH | |
| ? message.substring(0, IMPORTJSON_MAX_ERROR_LENGTH) + '…' | |
| : message; | |
| console.error(`${context} Error: ${message}`); | |
| return [['Error'], [trimmed]]; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment