首页 > 解决方案 > JSON POST 导入

问题描述

我正在尝试将 JSON POST API 中的数据导入 Google 表格。我已经能够记录完整的 JSON 响应,但现在无法将其过滤为我需要的属性,因为当我尝试记录 DIV1 时,我不断收到一条错误消息,指出该属性是“未定义”。我已经尝试测试它的其他参数,例如 DrawDate 和 DrawType,但仍然收到相同的消息。

function main() {

// Make a POST request with a JSON payload.
var data = {
  'CompanyId': 'GoldenCasket',
  'MaxDrawCount': 1,
  'OptionalProductFilter':['OzLotto']};

var options = {
  'method' : 'post',
  'contentType': 'application/json',
  // Convert the JavaScript object to a JSON string.
  'payload' : JSON.stringify(data)};

  var response = UrlFetchApp.fetch('https://data.api.thelott.com/sales/vmax/web/data/lotto/opendraws', options);

  Logger.log('output: '+ response);          

  var json = JSON.parse(response)
  var DIV1 = json["Div1Amount"];

  Logger.log(DIV1) 
}

我收到了对请求的回复,但我只想收到 Div1Amount。

output: 
{
   "Draws":[
      {
         "ProductId":"OzLotto",
         "DrawNumber":1323,
         "DrawDisplayName":"Oz Lotto $80,000,000",
         "DrawDate":"2019-06-25T00:00:00",
         "DrawLogoUrl":"http://media.tatts.com/TattsServices/Lotto/Products/OzLotto_v1.png",
         "DrawType":"Jackpot",
         "Div1Amount":80000000.0000,
         "IsDiv1Estimated":false,
         "IsDiv1Unknown":false,
         "DrawCloseDateTimeUTC":"2019-06-25T09:35:00",
         "DrawEndSellDateTimeUTC":"2019-06-25T09:30:00",
         "DrawCountDownTimerSeconds":538150.0
      }
   ],
   "ErrorInfo":null,
   "Success":true
}

标签: javascriptjsonpost

解决方案


在您的回复中,Div1Amount是 inisdeDraws列表。因此,要做到这一点,您必须获取列表并遍历列表然后var DIV1 = listObj["Div1Amount"];才能工作。示例代码:

//after `var json = JSON.parse(response)` line, change your code with this:

var drawList=json ["Draws"];
//now iterate the list:
for(var i=0;i<drawList.length;i++)
{
  var DIV1=drawList[i]["Div1Amount"];
  console.log(DIV1);
}

推荐阅读