Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Created May 25, 2022 08:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanaikech/d905b75175bd297733f807e7bddd33d4 to your computer and use it in GitHub Desktop.
Save tanaikech/d905b75175bd297733f807e7bddd33d4 to your computer and use it in GitHub Desktop.
Parsing JSON Data Array by Expanding Header Row using Google Apps Script

Parsing JSON Data Array by Expanding Header Row using Google Apps Script

This is a sample script for parsing JSON data array by expanding the header row using Google Apps Script.

Sample script

function myFunction() {
  const obj = [
    { key1: "value1", key2: "value2", key3: "value3" },
    { key4: "value1", key5: "value2", key6: "value3" },
    { key7: "value1", key8: "value2", key9: "value3" },
  ];

  const headers = Object.keys(
    obj.reduce((o, e) => (Object.keys(e).forEach((k) => (o[k] = true)), o), [])
  );
  const values = [headers, ...obj.map((o) => headers.map((k) => o[k] || null))];

  SpreadsheetApp.getActiveSheet()
    .clearContents()
    .getRange(1, 1, values.length, values[0].length)
    .setValues(values);
}

Testing

When this script is run, the following result is obtained. It is found that the header row is expanded by including all keys.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment