javascript - 访问不存在的属性的安全方法

标签 javascript json

我使用带有 JavaScript 代码的 Google Apps 脚本,运行 UrlFetchApp,从 Stripe API 提取数据以检索发票。然后,该脚本将 API 中的数据更新到 Google 表格模板中。

我遇到的问题是,如果 API 在客户的特定行上没有数据,则会破坏脚本。 API 将缺少数据存储为 NULL,例如,当客户的发票上没有折扣时,"discount": null

当脚本到达没有数据的行时,NULL 响应会中断脚本并停止运行。我想要做的是返回一个值,指定没有数据(例如:返回数字 0 表示没有折扣),并让脚本继续运行其余的代码行。

我的代码:

function getInvoiceObj() 
  {
    var apiKey, content, options, response, secret, url;

    secret = "rk_live_xxxxxxxxxxxxxxxxxx";
    apiKey = "xxxxxxxxxxxxxxxxx";

    url = "https://api.stripe.com/v1/invoices/in_xxxxxxxxxxxxx?expand[]=charge&expand[]=customer";

    options = {
      "method" : "GET",
      "headers": {
        "Authorization": "Bearer " + secret 
      },
      "muteHttpExceptions":true
    };

    response = UrlFetchApp.fetch(url, options);

    //Push data to Sheet from invoice. **Writes over existing Sheet data**
    content = JSON.parse(response.getContentText());
    var sheet = SpreadsheetApp.getActiveSheet();

     /* Customer Discount */

sheet.getRange(21,2).setValue([content.discount.coupon.percent_off]);
}

最佳答案

您可能正在寻找if

if(content.discount===null)
  sheet.getRange(21,2).setValue([0]);
else
  sheet.getRange(21,2).setValue([content.discount.coupon.percent_off]);

也许?:

sheet.getRange(21,2).setValue([
  content.discount===null?0:content.discount.coupon.percent_off
]);

关于javascript - 访问不存在的属性的安全方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55929046/

相关文章:

javascript - 在 ngDraggable 中获取目标 div 的属性

javascript - jquery自定义div来确认删除操作

javascript - AngularJS 策略防止类的无样式内容闪现

javascript - 如何在twig模板中使用assetic动态导出内联javascript?

java - 我如何在用java开发的rest web服务中返回json

javascript - 为什么我的 AngularJS Controller 定义和标记没有按预期工作? - <controller> 不是函数错误

javascript - 跟随超链接,如果超链接指向当前页面,则重新加载页面

php - 作为 JSON API 的 GUI 的 Chrome 扩展

json - 使用Golang的示例JSON响应

ios - Swift 和 JSON 只解析一个对象而不是一个数组