ImportJSON for Google Sheets: Crypto and Stock Prices

by Fahim Mahmud Chisti

Google Sheets has no built-in IMPORTJSON function, but a short Apps Script adds one, so you can pull crypto prices, stock quotes and FX rates from any JSON API into your sheet. You get the full function, working formulas for CoinGecko, Alpha Vantage, Finnhub and ExchangeRate.host, a way to refresh the data on a schedule, and fixes for the errors you will see.

Quick answer: Paste the IMPORTJSON custom function below into Extensions > Apps Script, store your API key as a script property, then call it like any formula. Custom functions do not refresh by themselves, so add a refresh cell or a time-driven trigger.

  1. Open Extensions > Apps Script, paste the IMPORTJSON code and save.
  2. In Project Settings > Script Properties, add your API key, for example as COINGECKO_KEY.
  3. In a cell, enter the CoinGecko formula from the recipes section with the path bitcoin.usd.
  4. Check the result: the cell should show the Bitcoin price in US dollars as a single number.
  5. Refresh it with a changing argument or a time-driven trigger that writes results on a schedule.
In this guide
  1. Why ImportJSON for Google Sheets
  2. Set up: a safe, readable ImportJSON function
  3. Core recipes: crypto, stocks, FX
  4. Refresh strategies and rate limits
  5. Dashboard ideas to build on top
  6. Reliability tips
  7. ImportJSON vs GOOGLEFINANCE vs add‑ons (comparison)
  8. Implementation guide: a crypto and stocks sheet in 30 minutes
  9. Security, terms, and compliance
  10. Common IMPORTJSON errors and fixes
  11. Frequently asked questions
  12. Next steps
  13. Official docs and trusted sources
  14. Related guides on IsItDev
ImportJSON for Google Sheets: pull live API data (crypto, stocks, FX) into dashboards
Import JSON from any HTTPS API into Sheets—then chart, alert, and share.

Why ImportJSON for Google Sheets

GOOGLEFINANCE is free and easy, but it does not cover every asset and its quotes can be delayed. An ImportJSON function calls any HTTPS API that returns JSON (the text format most web APIs answer in) and turns the response into rows and columns. You can pull:

  • Crypto tickers (BTC, ETH) from public APIs.
  • US/EU equities via quote endpoints.
  • FX, commodities, indexes, and even custom business APIs.
  • Operational metrics (app stats, server health) for live boards.

Set up: a safe, readable ImportJSON function

We’ll create a custom function named IMPORTJSON that accepts a URL, an optional dot-path selector (for example bitcoin.usd), and an optional Script Property name that holds an API key. It returns a clean 2D array you can chart or reference.
  1. Open your Google Sheet → Extensions → Apps Script.
  2. Delete any placeholder code and paste the function below.
  3. Click the Save icon (Ctrl/Cmd + S) and name the project ImportJSON.
/**
 * IMPORTJSON(url, [path], [keyProperty])
 * Fetches JSON from a URL and returns a 2D array.
 * path: optional dot path into the JSON, e.g. "bitcoin.usd".
 * keyProperty: optional name of a Script Property whose value (an API key)
 * is appended to the end of the URL, so the key never sits in a cell.
 * Examples:
 *   =IMPORTJSON("https://api.example.com/v1/items")
 *   =IMPORTJSON(A2, "data.items")
 *   =IMPORTJSON("https://api.example.com/v1/quote?symbol=AAPL&token=", "", "MY_API_KEY")
 * @customfunction
 */
function IMPORTJSON(url, path, keyProperty) {
  if (!url) return [["Error", "Missing URL"]];
  if (keyProperty) {
    var key = PropertiesService.getScriptProperties().getProperty(keyProperty);
    if (!key) return [["Error", "Script property not set: " + keyProperty]];
    url += encodeURIComponent(key);
  }
  var resp = UrlFetchApp.fetch(url, { muteHttpExceptions: true, followRedirects: true });
  var code = resp.getResponseCode();
  if (code < 200 || code >= 300) return [["HTTP", code]];
  var obj;
  try {
    obj = JSON.parse(resp.getContentText());
  } catch (e) {
    return [["Error", "Invalid JSON"]];
  }
  // Traverse by simple dot path, e.g. bitcoin.usd
  if (path) {
    var parts = String(path).split(".");
    for (var i = 0; i < parts.length; i++) {
      if (obj == null) break;
      obj = obj[parts[i]];
    }
  }
  return toTable_(obj);
}
// Convert a JSON value to a 2D table
function toTable_(value) {
  if (value == null) return [[""]];
  if (Array.isArray(value)) {
    if (value.length === 0) return [[""]];
    // Array of primitives
    if (typeof value[0] !== 'object' || value[0] === null) {
      var rows = value.map(function (v) {
        return [v];
      });
      return [["value"]].concat(rows);
    }
    // Array of objects: build a union header
    var keys = {};
    value.forEach(function (row) {
      Object.keys(row || {}).forEach(function (k) {
        keys[k] = true;
      });
    });
    var headerArr = Object.keys(keys);
    var out = [headerArr];
    value.forEach(function (row) {
      out.push(headerArr.map(function (k) {
        return getPrimitive_(row ? row[k] : null);
      }));
    });
    return out;
  }
  // Single object: two-column key/value table
  if (typeof value === 'object') {
    var kv = Object.keys(value).map(function (k) {
      return [k, getPrimitive_(value[k])];
    });
    return [["key", "value"]].concat(kv);
  }
  // Primitive: single cell
  return [[value]];
}
function getPrimitive_(v) {
  if (v == null) return "";
  if (typeof v === 'object') return JSON.stringify(v);
  return v;
}

Save, go back to the sheet and type =IMPORTJSON( in a cell: the function should appear in the autocomplete list. If it does not, the script was not saved or belongs to a different spreadsheet.

How IMPORTJSON turns JSON into cells

The optional path argument picks a part of the response. Take this sample response from a price API (made-up numbers): {"bitcoin": {"usd": 64000}, "ethereum": {"usd": 3100}}. Here is what each call returns:

path argumentWhat the cells show
"bitcoin.usd"One cell: 64000
"bitcoin"A key/value table: header key | value, then usd | 64000
"" (empty)Header key | value, then bitcoin | {"usd":64000} and ethereum | {"usd":3100} (nested objects are kept as JSON text)

If the response is a list of objects, such as a market-data endpoint with one object per coin, you get a header row with every field name, then one row per item. That is the easiest shape to feed into QUERY, charts and lookups.

Notes:
  • This function is intentionally minimal and readable. It returns headers and handles arrays/objects.
  • For APIs that take the key in the URL, pass the name of a Script Property as the third argument. For APIs that expect the key in a header, write a wrapper function that calls UrlFetchApp with a headers object.
  • A custom function must return within 30 seconds and only recalculates when one of its arguments changes, so it is not a live feed on its own (see the refresh strategies below).

Core recipes: crypto, stocks, FX

Always read the official API docs for parameter names, frequency limits, and terms of use. Many providers require API keys; store them in Script Properties (Apps Script editor → Project Settings → Script Properties), not in a cell. Anyone who can view the sheet can read a cell, even a protected one.

1) Crypto (CoinGecko)

CoinGecko's free Demo plan takes its key in the x_cg_demo_api_key URL parameter. Save the key as a script property named COINGECKO_KEY, then pull a single price:
=IMPORTJSON("https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd&x_cg_demo_api_key=", "bitcoin.usd", "COINGECKO_KEY")
Or a market-data table with one row per coin (verify docs and parameters):
=IMPORTJSON("https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&ids=bitcoin,ethereum&x_cg_demo_api_key=", "", "COINGECKO_KEY")

2) Stocks (keyed examples — confirm on official pages)

Alpha Vantage (latest quote; key saved as ALPHAVANTAGE_KEY):
=IMPORTJSON("https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=AAPL&apikey=", "Global Quote", "ALPHAVANTAGE_KEY")
Finnhub (quote; key saved as FINNHUB_KEY):
=IMPORTJSON("https://finnhub.io/api/v1/quote?symbol=MSFT&token=", "", "FINNHUB_KEY")

3) FX rates

ExchangeRate.host (now requires a free access key; save it as EXCHANGERATE_KEY and check their docs for the current parameters):

=IMPORTJSON("https://api.exchangerate.host/live?source=USD&currencies=EUR,GBP,JPY&access_key=", "quotes", "EXCHANGERATE_KEY")

Refresh strategies and rate limits

  • Manual refresh: a custom function only recalculates when one of its arguments changes, and volatile functions such as NOW() or RAND() are not allowed as arguments. Append a cell reference instead, e.g. =IMPORTJSON(B2 & "&ts=" & $Z$1), and change the value in Z1 when you want fresh data. If you also pass a key property, put the ts parameter before the key parameter, because the key is added to the very end of the URL: "…&ts=" & $Z$1 & "&x_cg_demo_api_key=".
  • Time‑driven triggers: Build a refresh sheet script that reads URLs and writes outputs to ranges, scheduled every N minutes. Respect quotas.
  • Caching: Store last response in CacheService for X seconds to avoid hammering APIs.
  • Backoff: If your provider returns HTTP 429, slow down. Exponential backoff protects your keys.
function FETCH_TO_RANGE() {
  var sheet = SpreadsheetApp.getActive().getSheetByName('Data');
  var url = sheet.getRange('B2').getValue();
  var out = IMPORTJSON(url);
  // Clear the previous output (row 5 down), then write the new table
  sheet.getRange(5, 1, sheet.getMaxRows() - 4, sheet.getMaxColumns()).clearContent();
  sheet.getRange(5, 1, out.length, out[0].length).setValues(out);
}
Schedule it in the Apps Script editor under Triggers (clock icon) → Add Trigger → Time-driven.

Dashboard ideas to build on top

1) Crypto + stocks blend board

  1. Tab Data: call 2–3 endpoints (crypto top coins, 3–5 tickers).
  2. Tab KPIs: summarize price, 24h change, pre‑market flags with QUERY.
  3. Charts: sparkline trends, bar of daily % changes, and traffic‑light conditional formatting.

2) Portfolio tracker with alerts

  1. Positions table: Ticker, Qty, Cost Basis.
  2. Live quotes via ImportJSON or GOOGLEFINANCE fallback.
  3. Alert rules: email when price crosses target (Apps Script MailApp).

3) FX exposure monitor

  1. Fetch USD→EUR/GBP/JPY hourly.
  2. Compute blended rate for invoices and set pricing guard rails.

Reliability tips

  • Prefer stable endpoints designed for polling; web page scrapes can break.
  • Normalize column headers; your charts and formulas won’t break when schemas expand.
  • Separate fetch from presentation. Keep a raw data tab and reference it from views.
  • Document keys and paths in a small data dictionary note next to your formulas.
  • Add slicers to the charts and pivot tables built on your imported range for interactive filtering (slicers do not change formula results).

ImportJSON vs GOOGLEFINANCE vs add‑ons (comparison)

  • GOOGLEFINANCE: Easy and free, but limited coverage and sometimes delayed.
  • ImportJSON + APIs: Maximum flexibility and coverage; you manage keys/limits.
  • Marketplace add‑ons: Polished UX and scheduling; verify vendor reliability and pricing on official pages.

Implementation guide: a crypto and stocks sheet in 30 minutes

  1. Install function: add IMPORTJSON script above.
  2. Create Data tab: list endpoints in column B; use =IMPORTJSON(B2) outputs below.
  3. Clean & label: use INDEX, FILTER, and LET to shape tidy tables.
  4. KPIs tab: pull last price, 24h change; add =SPARKLINE() for quick trends.
  5. Charts + Slicers: build bar/line charts and slicers for ticker/sector.

Security, terms, and compliance

  • Keys: store them in Script Properties, not in cells (a protected range is still readable by anyone who can view the sheet). Editors can open the script project and read script properties, so give edit access only to people you trust.
  • Terms: ensure your use complies with each provider’s ToS; many restrict redistribution.
  • Quotas: respect provider rate limits, and note that Apps Script itself allows 20,000 URL Fetch calls per day on consumer accounts (100,000 on Google Workspace); add caching and scheduled fetches.

Common IMPORTJSON errors and fixes

  • #NAME? “Unknown function”: the script is not saved, or it lives in another spreadsheet’s script project. Custom functions only work in the spreadsheet whose Extensions > Apps Script editor holds them.
  • HTTP | 401 or HTTP | 403: the API rejected the key. Check the script property name in the third argument, and that the URL ends with the key parameter and an = sign.
  • HTTP | 429: too many requests. Refresh less often, batch several symbols into one call, or cache responses.
  • Error | Script property not set: …: the property name in the formula does not match one in Project Settings > Script Properties (names are case-sensitive).
  • Error | Invalid JSON: the URL returned a web page instead of JSON. Open the URL in a browser tab to see what comes back, and check the provider’s docs for the right endpoint.
  • #REF! “Array result was not expanded because it would overwrite data”: the output table needs empty cells below and to the right. Clear them or move the formula.
  • The price never changes: expected. A custom function recalculates only when its arguments change; use the refresh cell or the time-driven trigger above.

Frequently asked questions

Is ImportJSON an official Google function?

No. It is a custom Apps Script function you add to your spreadsheet yourself. It uses UrlFetchApp to call the API and JSON.parse to read the response, then returns a table. Because it lives in your script project, you can change it, but you also maintain it.

Why doesn’t my ImportJSON price update automatically?

Because custom functions only recalculate when one of their arguments changes, and volatile functions such as NOW() are not allowed as arguments. Add a refresh cell to the URL, or run the FETCH_TO_RANGE script on a time-driven trigger so new values are written on a schedule.

Will this work on shared or view-only sheets?

Yes, viewers see the values the function last returned. They cannot change its arguments, so for predictable updates use a time-driven trigger that writes fresh values into the sheet. Keep keys in Script Properties so viewers never see them in a cell.

Can I pass HTTP headers for authentication?

Not with the function as written; it only adds the key to the URL. Write a small wrapper that calls UrlFetchApp.fetch(url, {headers: {...}}), parse the response, and pass the result to toTable_. Read the key from Script Properties inside the wrapper.

Is GOOGLEFINANCE good enough for stocks?

For many personal trackers, yes: it is free, needs no key and covers major exchanges. Quotes can be delayed and coverage is limited, so use ImportJSON with an API when you need specific assets, more fields or data GOOGLEFINANCE does not offer.

Next steps

Start with the CoinGecko single-price formula, confirm it returns a number, then add a market-data table on a raw data tab. Shape that tab into a report with the Google Sheets QUERY function, and look up single prices by ticker with XLOOKUP. If an API returns results page by page, see how to fetch paginated API data in Apps Script.

Official docs and trusted sources

all_in_one_marketing_tool