如何使用Google Sheets应用脚本将JSON中的子字段添加到Google Sheets中

j0pj023g  于 2022-12-30  发布在  Go
关注(0)|答案(1)|浏览(153)
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.如何将json.data.map“weightTierInformation”下的“gramAmount”添加到“www.example.com“中:

"weightTierInformation": [
        {
          "name": "string",
          "gramAmount": 0,
          "pricePerUnitInMinorUnits": 0
        }   ]

1.如何将字段名存储在一个“var”中,这样我就不必将它们写在两个不同的位置?X=〉X

o2rvlv0m

o2rvlv0m1#

在你的情况下,下面的修改怎么样?

发件人:

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

收件人:

在本例中,所有行都用sku, quantity, productName, brand, gramAmount填充。

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

或者,在下面的情况下,每个第1行具有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])
);

相关问题