简体   繁体   English

如何使用 Google 表格应用程序脚本将 JSON 中的子字段添加到 Google 表格中

[英]How to add a sub-field from JSON into Google Sheets using Google Sheets app script

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);
    
  
   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);
  1. how can I add to the "json.data.map" the "gramAmount" which is under "weightTierInformation":如何将“weightTierInformation”下的“gramAmount”添加到“json.data.map”:
     "weightTierInformation": [
        {
          "name": "string",
          "gramAmount": 0,
          "pricePerUnitInMinorUnits": 0
        }   ]

  1. How can I store the fields names in a "var" so I won't have to write them in 2 different locations?如何将字段名称存储在“var”中,这样我就不必将它们写在两个不同的位置? X=>X X=>X

In your situation, how about the following modification?在您的情况下,以下修改如何?

From:从:

var values = json.data.map(({ sku, quantity, productName, brand }) => [sku, quantity, productName, brand]);

To:到:

In this case, all rows are filled by sku, quantity, productName, brand, gramAmount .在这种情况下,所有行都由sku, quantity, productName, brand, gramAmount填充。

var values = json.data.flatMap(({ sku, quantity, productName, brand, weightTierInformation }) =>
  weightTierInformation.map(({gramAmount}) => [sku, quantity, productName, brand, gramAmount])
);

Or, in the following case, each 1st row has sku, quantity, productName, brand, gramAmount , and other rows have null, null, null, null, gramAmount .或者,在以下情况下,每个第一行都有sku, quantity, productName, brand, gramAmount ,其他行有null, null, null, null, gramAmount

var values = json.data.flatMap(({ sku, quantity, productName, brand, weightTierInformation }) =>
  weightTierInformation.map(({gramAmount}, j) => j == 0 ? [sku, quantity, productName, brand, gramAmount] : [...Array(4).fill(null), gramAmount])
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM