Export JSON or an Apify dataset to Google Sheets automatically

Last updated · by Sharkinho Tools team

Recipe card

You get: A Google Sheet that fills itself with fresh rows after every scraper run

Time
10 minutes (one-time setup)
Difficulty
Easy
Tool
Google Sheets Export & Import

Ingredients

  • A Google account
  • A Google Cloud service account key (free)
  • The data: an Apify run, a JSON URL or inline JSON

Quick answer: Create a Google service account, share your sheet with its email, and have an exporter write each scraper run into the sheet with that key. Service accounts don't expire the way OAuth logins do, so scheduled exports keep working. You can do it with our Apify actor as a post-run integration, or with 40 lines of Python and gspread.

Most scraped data ends up in a spreadsheet, and the hard part isn't the writing. It's that the export keeps breaking: OAuth tokens expire, Google returns 429 on big batches, and a scraped cell starting with = turns into a formula. We built our exporter around those three problems. If you only need to move data once, skip all of this: download the CSV and use File → Import in Sheets.

What an export to Google Sheets looks like

Nested JSON is flattened into columns and lists become comma-separated text. Here is a test we ran on 22 November 2026: the top five Product Hunt launches from our Product Hunt recipe, sent as inline data. The run took 3.3 seconds and wrote 5 rows and 7 columns.

ranknametaglineupvoteswebsiteDomaintopics
1SaparoMuse for shopping with deals stacks341saparo.aiProductivity, E-Commerce, Tech
2TripmojoAgentic travel app that helps plan, book and run your trip309tripmojo.aiTravel, Artificial Intelligence
3DockerBuilt to run on trust, for the agentic era266docker.comDeveloper Tools, Artificial Intelligence, Security
4BookellaA reading tracker that helps you read more188bookella.appAndroid, iOS, Productivity
5CurrentsCurrents for Claude & Codex to see all your tests158currents.devSoftware Engineering, Developer Tools, GitHub

The seventh column, makers, held a list of objects and became JSON text. Use fields to pick and order columns.

Step 1: the service account (once, about 2 minutes)

Both methods below need this. Nothing here costs money.

  1. Open Google Cloud Console → Service accounts, create a project if asked, then Create service account. A name is enough. Skip the roles.
  2. Open the new account, go to Keys → Add key → Create new key → JSON. A .json file downloads. Treat it like a password.
  3. Enable the Google Sheets API for the same project.
  4. In your spreadsheet, click Share and add the service account email (it ends in iam.gserviceaccount.com) as Editor.

The two setup errors the actor reports map straight to steps 3 and 4: "Google Sheets API is not enabled" (enable it and wait a minute) and "Cannot access the spreadsheet" (you shared it with your own email, not the robot's).

Step 2a: no code, export every run automatically

Open the scraper whose results you want (any actor, ours or not), go to Integrations → Add integration → Actor and pick Google Sheets Export & Import. Set the Dataset field to {{resource.defaultDatasetId}} and Apify fills in the dataset of the run that just finished, so each successful run is pushed to your sheet. Input for a daily job scraper:

json
{
  "spreadsheet": "https://docs.google.com/spreadsheets/d/1AbC.../edit",
  "sheetName": "Jobs",
  "mode": "append-unique",
  "uniqueKey": "jobId",
  "datasetId": "{{resource.defaultDatasetId}}",
  "serviceAccountKey": "{ ...paste the whole JSON key... }"
}

append-unique is the mode that makes scheduled scrapers useful. Yesterday's jobs are already in the sheet, so only new jobIds get added. In append mode, new fields are added as columns on the right and existing columns never move, so formulas and charts that point at column C keep pointing at the right data.

To push data you already have, pick the dataset in the datasetId field, pass a jsonUrl, or paste the rows inline:

json
{
  "data": [
    { "rank": 1, "name": "Saparo", "upvotes": 341, "topics": ["Productivity", "E-Commerce", "Tech"] },
    { "rank": 2, "name": "Tripmojo", "upvotes": 309, "topics": ["Travel", "Artificial Intelligence"] }
  ],
  "mode": "replace"
}

Price: $0.0001 per row written or read, so 10,000 rows cost $1. Our 5-row test costs $0.0005 at list price. Rows go out in chunks of 5,000, and 429 or 5xx answers from Google are retried with backoff, so large exports finish.

Step 2b: DIY in Python with gspread

If your data already lives in a Python script, you don't need us. This takes any URL that returns a JSON array, flattens it and replaces a tab with it:

python
import json
import sys

import gspread
import requests


def flatten(obj, prefix=""):
    """{'seller': {'name': 'A'}} -> {'seller.name': 'A'}; lists become 'a, b'."""
    out = {}
    for key, value in obj.items():
        name = f"{prefix}{key}"
        if isinstance(value, dict):
            out.update(flatten(value, name + "."))
        elif isinstance(value, list):
            out[name] = ", ".join(
                json.dumps(v) if isinstance(v, (dict, list)) else str(v) for v in value)
        else:
            out[name] = "" if value is None else value
    return out


def to_rows(items):
    flat = [flatten(i) for i in items]
    header = []
    for row in flat:
        header += [k for k in row if k not in header]
    return [header] + [[row.get(k, "") for k in header] for row in flat]


def push(rows, spreadsheet_id, tab, key_file="service-account.json"):
    gc = gspread.service_account(filename=key_file)
    sh = gc.open_by_key(spreadsheet_id)
    try:
        ws = sh.worksheet(tab)
    except gspread.WorksheetNotFound:
        ws = sh.add_worksheet(title=tab, rows=len(rows) + 10, cols=len(rows[0]))
    ws.clear()
    # RAW = write values as-is, so scraped text like "=IMPORTXML(...)" never runs
    ws.update(rows, "A1", value_input_option="RAW")
    return len(rows) - 1


if __name__ == "__main__":
    items = requests.get(sys.argv[1], timeout=60).json()  # any URL returning a JSON array
    rows = to_rows(items)
    print(rows[0])
    print(rows[1])
    if len(sys.argv) > 2:
        print(push(rows, sys.argv[2], "Data"), "rows written")

Run it with python to_sheets.py <json-url> <spreadsheet-id> after putting the key file next to it as service-account.json. We tested the flattening on a small sample, including a hostile =IMPORTXML value:

python
from to_sheets import to_rows
items = [
 {"product": "Coffee beans 1kg", "price": 18.9, "tags": ["coffee", "beans"], "seller": {"name": "Roastery A", "country": "PT"}},
 {"product": "Espresso cups (6)", "price": 24.5, "inStock": False, "seller": {"name": "Shop B"}, "note": "=IMPORTXML(A1)"},
]
for r in to_rows(items): print(r)
output
['product', 'price', 'tags', 'seller.name', 'seller.country', 'inStock', 'note']
['Coffee beans 1kg', 18.9, 'coffee, beans', 'Roastery A', 'PT', '', '']
['Espresso cups (6)', 24.5, '', 'Shop B', '', False, '=IMPORTXML(A1)']

How we tested it: gspread 6.2.1 on Python 3.9, flattening checked with the sample above and the JSON URL path checked against a public JSON API. We also ran push() with a throwaway key to confirm the call chain reaches Google (it fails at auth with invalid_grant, as it should). With a real key it writes to the tab.

What the script doesn't do, and where people usually get hurt:

Other ways people do this

FAQ

Why use a service account instead of logging in with Google?

A service account is a robot Google account that authenticates with a key file. There is no consent screen and no refresh token that can be revoked or expire, so a scheduled export keeps working months later. You only have to share the spreadsheet with its email address.

How do I avoid duplicate rows when the scraper runs every day?

Use append-unique mode with a uniqueKey such as url, id or jobId. Only rows whose key is not already in the sheet are added. Plain append mode adds everything every time.

Can scraped text run formulas in my sheet?

Only if values are written as user input. By default the actor writes values raw, so a scraped string like =IMPORTXML(...) stays text. In the Python script the same protection comes from value_input_option="RAW".

How many rows can Google Sheets hold?

Google allows up to 10 million cells per spreadsheet and 50,000 characters per cell. In practice sheets get slow well before that. If you are past a few hundred thousand rows, a database or BigQuery is the better home.

Can I read a Google Sheet into Apify instead?

Yes. Set operation to read. The first row becomes the field names and every other row becomes a JSON item in the dataset, which you can feed to another actor, for example a list of URLs to scrape.

Written by the Sharkinho Tools team. We build and maintain these scrapers, and every table on this page comes from a run we did ourselves. If something here is out of date, the actor's Issues tab on Apify reaches us directly.