Home > database >  How to extract only multiple field from JSON into Google Sheets using Google Sheets app script
How to extract only multiple field from JSON into Google Sheets using Google Sheets app script

Time:12-27

function import_inventory_test(e) {
  var options = {
    "method": "GET",
    "headers": {
      'Content-Type': 'application/json',
      'Prefer': 'code=200',
      'Prefer': 'dynamic=true',
      "clientId": "1",
      "key": "1",
    }
  }
  var text = UrlFetchApp.fetch("https://stoplight.io/mocks/flowhub/public-developer-portal/24055485/v0/inventory?max=100", options).getContentText();
  var json = JSON.parse(text);

  // I added the below script.
  var values = json.data.map(({ sku }) => [sku]);
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1"); // Please set your sheet name.
  sheet.getRange(1, 1, values.length).setValues(values);
}

How can I populate a-d columns with the following fields (by that order): sku (A) quantity (B) productName (C) brand (D)

CodePudding user response:

In your script, when your script is modified, how about the following modification?

From:

var values = json.data.map(({ sku }) => [sku]);
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1"); // Please set your sheet name.
sheet.getRange(1, 1, values.length).setValues(values);

To:

var values = json.data.map(({ sku, quantity, productName, brand }) => [sku, quantity, productName, brand]);
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1"); // Please set your sheet name.
sheet.getRange(1, 1, values.length, values[0].length).setValues(values);

Note:

  • If you want to add and modify the values you need, in this case, please modify json.data.map(({ sku, quantity, productName, brand }) => [sku, quantity, productName, brand]).

Reference:

  • Related